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

其他回答

有一篇博客文章有简短的源代码示例,介绍了滥用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中指定的查询提供程序创建查询。

我最近遇到了IEnumerable v. IQueryable问题。所使用的算法首先执行IQueryable查询以获得一组结果。然后将这些元素传递给foreach循环,并将这些元素实例化为实体框架(Entity Framework, EF)类。然后在Linq to Entity查询的from子句中使用这个EF类,导致结果为IEnumerable。

我对EF和实体的Linq相当陌生,所以花了一段时间才弄清楚瓶颈是什么。使用MiniProfiling,我找到了查询,然后将所有单独的操作转换为单个IQueryable Linq for Entities查询。IEnumerable执行了15秒,IQueryable执行了0.5秒。其中涉及三个表,在阅读本文后,我相信IEnumerable查询实际上形成了三个表的交叉积并过滤了结果。

尝试使用IQueryables作为经验法则,分析您的工作,使您的更改可测量。

我们可以用同样的方法来使用它们,它们只是在性能上有所不同。

IQueryable仅以有效的方式对数据库执行。这意味着它创建了一个完整的选择查询,并且只获取相关的记录。

例如,我们想以名字以“Nimal”开头的前10名客户为例。在这种情况下,将生成select查询,从客户中选择名称为“Nimal%”的前10 *。

但是如果我们使用IEnumerable,查询就像select * from Customer,其中名称像' Nimal% ',前十位将在c#编码级别过滤(它从数据库中获取所有客户记录并将它们传递给c#)。

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

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

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

除了上面的,有趣的是,如果你使用IQueryable而不是IEnumerable,你可以得到异常:

如果products是一个IEnumerable,下面的工作很好:

products.Skip(-4);

然而,如果products是一个IQueryable对象,并且它试图从DB表中访问记录,那么你会得到这个错误:

offset子句中指定的偏移量不能为负。

这是因为构造了以下查询:

SELECT [p].[ProductId]
FROM [Products] AS [p]
ORDER BY (SELECT 1)
OFFSET @__p_0 ROWS

OFFSET不能为负值。