Returning IEnumerable vs. IQueryable

前端 未结 14 2507
梦毁少年i
梦毁少年i 2020-11-21 22:59

What is the difference between returning IQueryable vs. IEnumerable, when should one be preferred over the other?



        
14条回答
  •  长发绾君心
    2020-11-21 23:59

    There is a blog post with brief source code sample about how misuse of IEnumerable can dramatically impact LINQ query performance: Entity Framework: IQueryable vs. IEnumerable.

    If we dig deeper and look into the sources, we can see that there are obviously different extension methods are perfomed for IEnumerable:

    // 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 Where(
            this IEnumerable source, 
            Func predicate)
        {
            return (IEnumerable) 
                new Enumerable.WhereEnumerableIterator(source, predicate);
        }
    }
    

    and IQueryable:

    // 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 Where(
            this IQueryable source, 
            Expression> predicate)
        {
            return source.Provider.CreateQuery(
                Expression.Call(
                    null, 
                    ((MethodInfo) MethodBase.GetCurrentMethod()).MakeGenericMethod(
                        new Type[] { typeof(TSource) }), 
                        new Expression[] 
                            { source.Expression, Expression.Quote(predicate) }));
        }
    }
    

    The first one returns enumerable iterator, and the second one creates query through the query provider, specified in IQueryable source.

提交回复
热议问题