Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does IList<> have fewer features than List<>?

To use such great function as ConvertAll(), I have to convert IList to List, it's painful.

like image 925
Benny Avatar asked Mar 13 '10 14:03

Benny


People also ask

When should I use IList or List?

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."

Why IEnumerable is faster than List?

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.

Why do we use IList in C#?

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.

How to fetch data from List in c#?

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.


2 Answers

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.

like image 162
mnemosyn Avatar answered Sep 18 '22 06:09

mnemosyn


Why don't use IEnumerable<T>.Select instead of List<T>.ConvertAll? Since IList inherits IEnumerable. See this question on SO.

like image 27
abatishchev Avatar answered Sep 20 '22 06:09

abatishchev