To use such great function as ConvertAll()
, I have to convert IList
to List
, it's painful.
IList<T> communicates "I need to get and set the elements of this sequence in arbitrary order". List<T> communicates "I need to get and set the elements of this sequence in arbitrary order and I only accept lists; I do not accept arrays."
IEnumerable is a deferred execution while List is an immediate execution. IEnumerable will not execute the query until you enumerate over the data, whereas List will execute the query as soon as it's called. Deferred execution makes IEnumerable faster because it only gets the data when needed.
In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.
We can use the foreach loop to go through all the items and read them. The following code snippet reads all items of a list and prints them on the console. We can also use a var keyword for any kind of data type. The following code snippet creates a new list and reads all of its items and displays on the console.
Note that List<>
is an implementation of IList<>
with actual storage, i.e. it holds an array in the background. In general, an IList<>
can be a proxy to something else. In db4o and linq to sql, your IList<>
could 'point to a query', i.e. accessing the list will trigger a database operation.
This way, you can perform myList.Skip(600).Take(20);
to perform pagination and only in this step will the actual query be executed. A List<>
containing a million entries will be huge, while there may be IList<>
s that have a huge Count
, but don't eat a significant amount of memory - as long as you don't access the elements.
ConvertAll
will require each and every object be instantiated so it is a costly operation. Thus, it is better to make the operation explicit and force you to retrieve a specific implementation of the interface. Obviously, conversion requires all objects to be instantiated anyway, so there's no benefit in doing it lazily.
Why don't use IEnumerable<T>.Select
instead of List<T>.ConvertAll
? Since IList
inherits IEnumerable
. See this question on SO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With