在LINQ查询中多久评估一次子句内? [英] How often is the In-Clause evaluated in a LINQ query?

查看:40
本文介绍了在LINQ查询中多久评估一次子句内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在另一个问题上回答了以下内容LINQ查询,该查询返回某些字符串组合的列表:

I just answered on another question with the following LINQ query, that returns a list of certain string combinations:

public static List<String> Combis(string value)
{   
  var combis =
    from bool1 in new bool[] {true, false}
    from bool2 in new bool[] {true, false}
    let i1 = 1
    let i2 = 1
    from i3 in new int[] {10, 20, 30}
    select value + "_" + bool1 + "_" + bool2 + "_" + i1 + "_" + i2 + "_" + i3;

  return combis.ToList();
}

我现在问自己:每个子句(例如,... in new bool[] {true, false})仅被评估一次还是多次,即每个子句中仅创建一个由多个数组组成的数组?

What I now ask myself: Is each in-clause (e.g., ... in new bool[] {true, false}) evaluated only once or multiple times, i.e., is there only one array created of multiple ones per in-clause?

更新:

正如答案所示,它被多次评估.我将代码更改为

As the answers indicate, it is evaluated multiple times. I will change the code to

public static List<String> Combis(string value)
{
    bool[] bools = new[] {true, false};
    int[] ints = new[] {10, 20, 30};

    var combis =
        from bool1 in bools
        from bool2 in bools
        let i1 = 1
        let i2 = 1
        from i3 in ints
        select value + "_" + bool1 + "_" + bool2 + "_" + i1 + "_" + i2 + "_" + i3;

    return combis.ToList();
}

因此不必创建多个数组.

so that no multiple arrays have to be created.

推荐答案

它被多次评估.查询表达式具有对方法调用的指定转换.我使用Resharper进行了转换.睁开你的眼睛...

It is evaluated multiple times. Query expressions have a specified translation to method calls. I used Resharper to perform that conversion. Avert your eyes...

new bool[] { true, false }
.SelectMany(bool1 => new bool[] { true, false }, (bool1, bool2) => new { bool1, bool2 })
.Select(@t => new { @t, i1 = 1 })
.Select(@t => new { @t, i2 = 1 })
.SelectMany(@t => new int[] { 10, 20, 30 }, (@t, i3) => "" + "_" + @t.@t.@t.bool1 + "_" + @t.@t.@t.bool2 + "_" + @t.@t.i1 + "_" + @t.i2 + "_" + i3);

对于每个bool1,正在创建一个新数组.

For each bool1, a new array is being created.

真的没有其他办法了.如果您写了以下内容怎么办?

It really can't be any other way. What if you had written the following?

from bool1 in new [] { true, false }
from bool2 in new [] { bool1 } //dependent on bool1!

可以根据范围内的所有范围变量生成内部序列.它是动态的.

The inner sequence can be generated depending on all range variables that are in scope. It is dynamic.

不过,C#编译器能否优化这一点?不能这样做是因为不允许人们知道Enumerable.SelectMany不取决于传入的序列的对象标识.例如,它可以将每个哈希码打印到控制台.

Could the C# compiler optimize this away, though? It can't because it is not allowed to know that Enumerable.SelectMany does not depend on the object identity of the sequences passed in. It could, for example, print each hash code to the console.

这篇关于在LINQ查询中多久评估一次子句内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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