Practical difference between List and IEnumerable

This question already has an answer here:

  • IEnumerable vs List - What to Use? How do they work? 9 answers

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


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

    链接地址: http://www.djcxy.com/p/28064.html

    上一篇: Cookie阻止/未保存在Internet Explorer的IFRAME中

    下一篇: List和IEnumerable之间的实际区别