Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between List<string> and IEnumerable<String>? [duplicate]

Tags:

c#

.net

Possible Duplicate:
What's the difference between IEnumerable and Array, IList and List?

What's the difference between the above two?

like image 297
user496949 Avatar asked Nov 15 '10 01:11

user496949


People also ask

What is the difference between IEnumerable and 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 we use IEnumerable instead of list?

We aren't forcing the caller to convert their data structure to a List unnecessarily. So it isn't that IEnumerable<T> is more efficient than list in a "performance" or "runtime" aspect. It's that IEnumerable<T> is a more efficient design construct because it's a more specific indication of what your design requires.

What is IEnumerable string in C#?

IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.

Is IEnumerable list or array?

IEnumerable is read-only and List is not. IEnumerable types have a method to get the next item in the collection.


2 Answers

A List<string> is a concrete implementation of IEnumerable<string>. The difference is that IEnumerable<string> is merely a sequence of string but a List<string> is indexable by an int index, can be added to and removed from and have items inserted at a particular index.

Basically, the interface IEnumerable<string> lets you stream the string in the sequence but List<string> lets you do this as well as modify and access the items in the lists in specific ways. An IEnumerable<string> is general sequence of string that can be iterated but doesn't allow random access. A List<string> is a specific random-access variable-size collection.

like image 107
jason Avatar answered Oct 02 '22 19:10

jason


different.

IEnumerable enables you to iterate through the collection using a for-each loop.

And IEnumerable just have method GetEnumerator.

And List it implement many interface like IEnumerable, Ilist, etc. So many function in List.

In performance IEnumerable faster than List.

like image 35
aeruL Avatar answered Oct 02 '22 20:10

aeruL