IList vs IEnumerable for Collections on Entities

廉价感情. 提交于 2019-11-26 19:23:14
Matt Hamilton

IEnumerable<T> represents a series of items that you can iterate over (using foreach, for example), whereas IList<T> is a collection that you can add to or remove from.

Typically you'll want to be able to modify an Order by adding or removing OrderLines to it, so you probably want Order.Lines to be an IList<OrderLine>.

Having said that, there are some framework design decisions you should make. For example, should it be possible to add the same instance of OrderLine to two different orders? Probably not. So given that you'll want to be able to validate whether an OrderLine should be added to the order, you may indeed want to surface the Lines property as only an IEnumerable<OrderLine>, and provide Add(OrderLine) and Remove(OrderLine) methods which can handle that validation.

Most of the time I end up going with IList over IEnumerable because IEnumerable doesn't have the Count method and you can't access the collection through an index (although if you are using LINQ you can get around this with extension methods).

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