What should I use an IEnumerable or IList? [duplicate]

空扰寡人 提交于 2019-11-27 20:50:20

问题


This question already has an answer here:

  • IList vs IEnumerable for Collections on Entities 2 answers

Can anyone tell me when I should use either.

For example, I think I should use an IList when I want to access the .Count of the collection or an individual item, correct?

Thank you.


回答1:


Generally speaking, you should try and use the least specific type that suits your purpose. IEnumerable is less specific than IList (IList implements IEnumerable) so unless you want something specific from IList (such as Count as you suggest, or perhaps Add, Delete, etc), I'd use IEnumerable.

One benefit of remaining with IEnumerable is that you can write iterator methods to return this type (look up "yield return" and iterator methods if you are not familiar with them). This allows you to write very memory efficient "pipelines" for your loops.




回答2:


You use IEnumerable when you want to loop through the items in a collection.

IList is when you want to add, remove, and access the list contents out of order.

IList vs IEnumerable for Collections on Entities

http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=722




回答3:


You should use IList when you need access by index to your collection, add and delete elements, etc., and IEnumerable when you need just enumerate over your collection.

A very simple answer, I can extend it if you will describe you scenario.



来源:https://stackoverflow.com/questions/3228708/what-should-i-use-an-ienumerable-or-ilist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!