单个LINQ查询中生成的迭代次数 [英] Numbers of iteration generated in a single LINQ query

查看:52
本文介绍了单个LINQ查询中生成的迭代次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用LINQ时,我总是有一个疑问.

I always have a question about LINQ when using it.

为以下代码(测试是列表)生成了多少个迭代器:

How many iterators have been generated for the following code (test is a List):

        var result = from t in test
                     where t.Length > 0 && t.Length < 5
                     orderby t[0]
                     select t;

据我所知,此查询被编译为:

As far as I know, this query is compiled as:

        var result2 = test.Where(t => t.Length > 0).Where(t => t.Length < 5).OrderBy(t => t[0]);

我检查了.NET源代码,发现Where实现简单地调用谓词函数并产生结果:

I examined the .NET source code and found the Where implementation simply calls the predicate function and yield the result:

    private static IEnumerable<TSource> WhereIterator<TSource>(IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
    {
        int iteratorVariable0 = -1;
        foreach (TSource iteratorVariable1 in source)
        {
            iteratorVariable0++;
            if (predicate(iteratorVariable1, iteratorVariable0))
            {
                yield return iteratorVariable1;
            }
        }
    }

我相信Microsoft以类似的方式实现OrderBy和其他功能(我想是OrderBy的OrderedEnumerable).

I believe Microsoft implements OrderBy and other functions a similar way like this (OrderedEnumerable for OrderBy I suppose).

这是否意味着LINQ将为此单个查询创建多个枚举器,这意味着列表中的某些内容将被复制多次? (yield return语句会将元素复制到我想的列表中吗?)

Does this mean LINQ will create multiple enumerators for this single query, which means some contents of my list will be copied several times? (The yield return statement will copy the element to a List I suppose?)

推荐答案

实际上,您的查询将被编译为单个Where运算符:

Actually your query will be compiled into single Where operator:

var result2 = test.Where(t => t.Length > 0 && t.Length < 5).OrderBy(t => t[0]);

总共将创建两个枚举器:

And totally two enumerators will be created:

  • 一个用于通过谓词过滤源的
  • 一个用于枚举过滤源以对项目进行排序的

这篇关于单个LINQ查询中生成的迭代次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆