C# List 和 IEnumerable 的实际区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17448812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Practical difference between List and IEnumerable
提问by Robin
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.
通过阅读类似的帖子,我了解到列表是一种 IEnumerable。但我真的很想知道这两者之间的实际区别是什么。
To someone who always have used a List and never used IEnumerable:
对于一直使用 List 而从未使用过 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!
希望有人可以为我解决这个问题或为我指明正确的方向。提前致谢!
采纳答案by Scott Lawrence
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.
IEnumerable 和 List 之间的一个重要区别(除了一个是接口,另一个是具体类)是 IEnumerable 是只读的,而 List 不是。
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.
因此,如果您需要能够对您的集合进行任何类型的永久更改(添加和删除),您将需要 List。如果您只需要阅读、排序和/或过滤您的收藏,IEnumerable 就足够了。
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.
因此,在您的实际示例中,如果您想一次添加四个字符串,则需要 List。但是如果你一次性实例化你的集合,你可以使用 IEnumerable。
IEnumerable firstFourLettersOfAlphabet = new[]{"a","b","c","d"};
You could then use LINQ to filter or sort the list however you wanted.
然后,您可以根据需要使用 LINQ 过滤或排序列表。
回答by DasDave
Many types other than List<T>implement IEnumerablesuch as an ArrayList. So one advantage is you can pass different collection types to the same function.
除了List<T>实现之外的许多类型,IEnumerable例如ArrayList. 所以一个优点是你可以将不同的集合类型传递给同一个函数。

