返回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;

两者都将被延迟执行,何时应该优先于其中一个?


当前回答

“IEnumerable”和“IQueryable”之间的主要区别在于在哪里执行筛选逻辑。一个在客户端(内存中)执行,另一个在数据库中执行。

例如,我们可以考虑一个例子,我们的数据库中有一个用户的10,000条记录,假设只有900个是活动用户,所以在这种情况下,如果我们使用“IEnumerable”,那么首先它将所有10,000条记录加载到内存中,然后应用IsActive筛选器,最终返回900个活动用户。

而另一方面,在同样的情况下,如果我们使用“IQueryable”,它将直接应用数据库上的IsActive过滤器,直接从那里将返回900个活跃用户。

其他回答

“IEnumerable”和“IQueryable”之间的主要区别在于在哪里执行筛选逻辑。一个在客户端(内存中)执行,另一个在数据库中执行。

例如,我们可以考虑一个例子,我们的数据库中有一个用户的10,000条记录,假设只有900个是活动用户,所以在这种情况下,如果我们使用“IEnumerable”,那么首先它将所有10,000条记录加载到内存中,然后应用IsActive筛选器,最终返回900个活动用户。

而另一方面,在同样的情况下,如果我们使用“IQueryable”,它将直接应用数据库上的IsActive过滤器,直接从那里将返回900个活跃用户。

之前已经说了很多,但回到根源,以一种更专业的方式:

IEnumerable是一个在内存中可以枚举的对象的集合——一个在内存中的序列,使得迭代成为可能(使得在每一个循环中都很容易,尽管你可以只使用IEnumerator)。它们就这样存在于记忆中。 IQueryable是一个表达式树,它将在某个时刻被转换成其他东西,并具有枚举最终结果的能力。我想这就是大多数人困惑的地方。

它们显然有着不同的内涵。

IQueryable表示一个表达式树(简单地说,就是一个查询),一旦调用了发布api,它就会被底层查询提供者转换成其他东西,比如LINQ聚合函数(Sum, Count等)或ToList[数组,字典,…]。IQueryable对象也实现了IEnumerable, IEnumerable<T>,因此如果它们表示一个查询,那么该查询的结果可以被迭代。这意味着IQueryable不只是查询。正确的术语是它们是表达式树。

现在,这些表达式如何执行以及它们转向什么都取决于所谓的查询提供者(我们可以想到表达式执行器)。

在实体框架世界(即神秘的底层数据源提供程序或查询提供程序)中,IQueryable表达式被转换为本地T-SQL查询。Nhibernate对它们做了类似的事情。例如,您可以按照《LINQ:构建IQueryable Provider链接》中描述的概念编写自己的查询工具,并且您可能希望为您的产品存储提供者服务提供一个自定义查询API。

基本上,IQueryable对象一直在被构造直到我们显式地释放它们并告诉系统把它们重写成SQL或者其他什么然后发送到执行链进行后续处理。

就像延迟执行一样,它是一个LINQ特性,在内存中保留表达式树方案,并仅在需要时将其发送到执行中,无论何时针对序列调用某些api(相同的Count、ToList等)。

The proper usage of both heavily depends on the tasks you're facing for the specific case. For the well-known repository pattern I personally opt for returning IList, that is IEnumerable over Lists (indexers and the like). So it is my advice to use IQueryable only within repositories and IEnumerable anywhere else in the code. Not saying about the testability concerns that IQueryable breaks down and ruins the separation of concerns principle. If you return an expression from within repositories consumers may play with the persistence layer as they would wish.

A little addition to the mess :) (from a discussion in the comments)) None of them are objects in memory since they're not real types per se, they're markers of a type - if you want to go that deep. But it makes sense (and that's why even MSDN put it this way) to think of IEnumerables as in-memory collections whereas IQueryables as expression trees. The point is that the IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. So, in fact, you can't really call any IEnumerable member without having the object in the memory. It will get in there if you do, anyways, if it's not empty. IQueryables are just queries, not the data.

总的来说,我建议以下几点:

如果您想让开发人员使用您的方法在执行之前细化您返回的查询,则返回IQueryable<T>。 如果您想传输一组对象来枚举,则返回IEnumerable。

想象一下IQueryable是什么——一个数据的“查询”(如果你想,你可以对它进行细化)。IEnumerable是一组对象(已经接收到或创建了),可以对其进行枚举。

有一篇博客文章有简短的源代码示例,介绍了滥用IEnumerable<T>如何极大地影响LINQ查询性能:实体框架:IQueryable vs. IEnumerable。

如果我们深入挖掘并查看源代码,我们可以看到对于IEnumerable<T>有明显不同的扩展方法:

// Type: System.Linq.Enumerable
// Assembly: System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Core.dll
public static class Enumerable
{
    public static IEnumerable<TSource> Where<TSource>(
        this IEnumerable<TSource> source, 
        Func<TSource, bool> predicate)
    {
        return (IEnumerable<TSource>) 
            new Enumerable.WhereEnumerableIterator<TSource>(source, predicate);
    }
}

和这个IQueryable < T >:

// Type: System.Linq.Queryable
// Assembly: System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Core.dll
public static class Queryable
{
    public static IQueryable<TSource> Where<TSource>(
        this IQueryable<TSource> source, 
        Expression<Func<TSource, bool>> predicate)
    {
        return source.Provider.CreateQuery<TSource>(
            Expression.Call(
                null, 
                ((MethodInfo) MethodBase.GetCurrentMethod()).MakeGenericMethod(
                    new Type[] { typeof(TSource) }), 
                    new Expression[] 
                        { source.Expression, Expression.Quote(predicate) }));
    }
}

第一个返回可枚举的迭代器,第二个通过IQueryable source中指定的查询提供程序创建查询。

除了前两个非常好的答案(由driis和Jacob):

IEnumerable 接口在系统中。集合名称空间。

IEnumerable对象表示内存中的一组数据,并且只能根据这些数据向前移动。由IEnumerable对象表示的查询立即完整地执行,因此应用程序可以快速地接收到数据。

当执行查询时,IEnumerable加载所有数据,如果我们需要对其进行筛选,筛选本身是在客户端完成的。

可查询接口位于系统中。Linq命名空间。

IQueryable对象提供了对数据库的远程访问,并允许您以从头到尾的直接顺序或反向顺序在数据中导航。在创建查询的过程中,返回的对象是IQueryable,查询是优化的。因此,在执行过程中消耗的内存更少,网络带宽更少,但同时它的处理速度比返回IEnumerable对象的查询稍微慢一些。

选择什么?

如果您需要返回的整个数据集,那么最好使用IEnumerable,它提供了最大的速度。

如果你不需要整个返回的数据集,而只是一些过滤后的数据,那么最好使用IQueryable。