问题描述
返回IQueryable<T>
与IEnumerable<T>
有什么区别,什么时候应该优先选择另一个?
What is the difference between returning IQueryable<T>
vs. IEnumerable<T>
, when should one be preferred over the other?
IQueryable<Customer> custs = from c in db.Customers
where c.City == "<City>"
select c;
IEnumerable<Customer> custs = from c in db.Customers
where c.City == "<City>"
select c;
推荐答案
是的,两者都会为您提供推迟执行.
Yes, both will give you deferred execution.
区别在于 IQueryable<T>
是允许LINQ-to-SQL(实际上是LINQ-to-任何东西)都可以工作.因此,如果您在 IQueryable<T>
上进一步优化查询,则该查询如果可能,将在数据库中执行.
The difference is that IQueryable<T>
is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>
, that query will be executed in the database, if possible.
对于 IEnumerable<T>
情况,将是LINQ-到对象,这意味着所有与原始查询匹配的对象都必须从数据库加载到内存中.
For the IEnumerable<T>
case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.
在代码中:
IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
该代码将执行SQL,仅选择金牌客户.另一方面,以下代码将在数据库中执行原始查询,然后过滤掉内存中的非黄金客户:
That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:
IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
这是非常重要的区别,并且正在 IQueryable<T>
在许多情况下可以避免您从数据库返回太多行.另一个主要的示例是进行分页:如果您使用 Take
和< Skip
.com/en-us/library/system.linq.iqueryable.aspx"rel =" noreferrer> IQueryable
,您只会得到请求的行数;在 IEnumerable<T>
上执行此操作将导致所有行加载到内存中.
This is quite an important difference, and working on IQueryable<T>
can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take
and Skip
on IQueryable
, you will only get the number of rows requested; doing that on an IEnumerable<T>
will cause all of your rows to be loaded in memory.
这篇关于返回IEnumerable< T>与IQueryable< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!