简体   繁体   English

IQueryable的优点 <T> IList <T>

[英]Advantages of IQueryable<T> over IList<T>

在C#DAL中,如果我返回IQueryable而不是IList,我将获得什么样的优势,Iam没有使用Entity Framework / N Hibernate,只是普通的旧ADO.Net ..

I believe returning an IQueryable allows lazy enumeration, whilst returning an IList doesn't. 我相信返回IQueryable允许惰性枚举,而返回IList则不行。

If you return an IList, the query against the database is performed at the point the DAL returns the IList. 如果返回IList,则在DAL返回IList时执行针对数据库的查询。 Returning an IQueryable, the return can be passed around and the query is only executated when you inspect the contents of the IQueryable. 返回IQueryable,返回可以传递,只有在检查IQueryable的内容时才会执行查询。

(This is based on my experience of LINQ to SQL - but I've not checked this against a definitive source) (这是基于我对LINQ to SQL的经验 - 但我没有根据权威来源对此进行检查)

You can keep querying against IQueryable. 您可以继续查询IQueryable。 IQueryable is not for your final return type but good for private helpers which build on original queries - reusable, composable pieces of queries that have an expected return type of the underlying type in your IQueryable<>. IQueryable不适用于您的最终返回类型,但适用于基于原始查询的私有帮助程序 - 可重用,可组合的查询片段,其IQueryable <>中具有基础类型的预期返回类型。

You should return an IEnumerable instead of IList or IQueryable: 您应该返回IEnumerable而不是IList或IQueryable:

IQueryable makes the caller think they can use lazy evaluation and add filters, sorting, projection, etc. IQueryable使调用者认为他们可以使用延迟评估并添加过滤器,排序,投影等。

IList allows the caller to add, remove, reverse, set values, and otherwise modify the returned collection. IList允许调用者添加,删除,反转,设置值,以及以其他方式修改返回的集合。 This might not be a problem for you, but if you plan on sharing data between calls then you need to watch out for this 这对您来说可能不是问题,但如果您计划在呼叫之间共享数据,那么您需要注意这一点

IEnumerable provides the caller an immutable collection which they know doesn't not support lazy evaluation. IEnumerable为调用者提供了一个不可变的集合,他们知道这些集合不支持延迟评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM