80

By reading similar posts I've learned that a List is a type of IEnumerable. But I'm really wondering what the practical difference between those two actually is.

To someone who always have used a List and never used IEnumerable:

  • What is the practical difference between the two?
  • In what scenarios is one of them better than the other?

Here is a practical example: We want to store four strings, order them alphabetically, pass them to another function and then show the user the result. What would we use and why?

Hopefully someone can sort this out for me or point me in the right direction. Thanks in advance!

4

2 回答 2

229

One important difference between IEnumerable and List (besides one being an interface and the other being a concrete class) is that IEnumerable is read-only and List is not.

So if you need the ability to make permanent changes of any kind to your collection (add & remove), you'll need List. If you just need to read, sort and/or filter your collection, IEnumerable is sufficient for that purpose.

So in your practical example, if you wanted to add the four strings one at a time, you'd need List. But if you were instantiating your collection all at once, you could use IEnumerable.

IEnumerable firstFourLettersOfAlphabet = new[]{"a","b","c","d"};

You could then use LINQ to filter or sort the list however you wanted.

于 2013-07-03T13:15:24.190 回答
14

Many types other than List<T> implement IEnumerable such as an ArrayList. So one advantage is you can pass different collection types to the same function.

于 2013-07-03T13:07:05.073 回答