返回IQueryable<T>和IEnumerable<T>之间的区别是什么,什么时候应该优先于另一个?
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;
两者都将被延迟执行,何时应该优先于其中一个?
一般来说,您希望保留查询的原始静态类型,直到有必要。
出于这个原因,你可以将你的变量定义为'var',而不是IQueryable<>或IEnumerable<>,你会知道你没有改变类型。
如果您开始使用IQueryable<>,通常希望将其保留为IQueryable<>,直到有一些令人信服的理由更改它。这样做的原因是您希望为查询处理器提供尽可能多的信息。例如,如果你只打算使用10个结果(你已经调用Take(10)),那么你想让SQL Server知道这一点,这样它就可以优化它的查询计划,只向你发送你将使用的数据。
A compelling reason to change the type from IQueryable<> to IEnumerable<> might be that you are calling some extension function that the implementation of IQueryable<> in your particular object either cannot handle or handles inefficiently. In that case, you might wish to convert the type to IEnumerable<> (by assigning to a variable of type IEnumerable<> or by using the AsEnumerable extension method for example) so that the extension functions you call end up being the ones in the Enumerable class instead of the Queryable class.
是的,两者都会让你延期执行。
区别在于IQueryable<T>是允许LINQ-to- sql (LINQ. sql)的接口。对任何事情)去工作。因此,如果在IQueryable<T>上进一步细化查询,该查询将在数据库中执行(如果可能的话)。
对于IEnumerable<T>情况,它将是LINQ-to-object,这意味着所有与原始查询匹配的对象都必须从数据库加载到内存中。
在代码:
IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
该代码将只对选择的黄金客户执行SQL。另一方面,下面的代码将在数据库中执行原始查询,然后在内存中过滤出非黄金客户:
IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
这是一个非常重要的区别,在许多情况下,使用IQueryable<T>可以避免从数据库返回太多行。另一个主要的例子是分页:如果你在IQueryable上使用Take和Skip,你将只得到请求的行数;在IEnumerable< t>上这样做会导致你所有的行都被载入内存。