Linq IList vs Concrete Interfaces

Now

IList<string> listOfStrings = (new string[] { "bob","mary"}); 

We cannot reform

 listOfStrings.ToList().ForEach(i => i.DoSome(i))); 

We need to redo the concrete implementation of the interface

 List<string> listOfStrings = ((new string[] { "bob","mary"}).ToLIst(); 

Then we can do a for each

 listOfStrings.ForEach(i => i.DoSome(i))); 

This is because the foreach statement does not work with the IList interface and why is this?

+4
source share
2 answers

You do not use the foreach operator - you use the foreach method, which is declared in List<T> (here) , as well as for arrays . There is no such extension method on IList<T> or IEnumerable<T> . You can write one, but personally I would use a real foreach :

 foreach (var text in listOfStrings) { ... } 

See the Eric Lippert blog post in the topic for thought, which is clearer than mine.

+8
source

Method ForEach List<T>.ForEach . This is not a method defined on IList<T> .


However, your first example does work:

 listOfStrings.ToList().ForEach(i => i.DoSome(i))); 

The Enumerable.ToList method returns a List<T> , which allows you to actually work fine.

However, you could not:

// Error during compilation listOfStrings.ForEach (i => i.DoSome (i)));

Because it directly uses IList<T> , which does not have a specific ForEach method.

+3
source

Source: https://habr.com/ru/post/1385609/


All Articles