gpt4 book ai didi

c# - In-Clause 在 LINQ 查询中多久计算一次?

转载 作者:行者123 更新时间:2023-11-30 16:50:31 25 4
gpt4 key购买 nike

我刚刚在 another question 上回答过使用以下 LINQ 查询,返回特定字符串组合的列表:

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-clause(例如,... in new bool[] {true, false})只被评估一次还是多次,即是否只有每个 in-clause 由多个数组创建一个数组?


更新:

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

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();
}

因此不必创建多个数组。

最佳答案

它被评估了多次。查询表达式对方法调用有特定的转换。我使用 Resharper 执行该转换。移开你的眼睛......

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,都会创建一个新数组。

真的没有别的办法了。如果您编写了以下内容会怎样?

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

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

不过,C# 编译器可以优化它吗?它不能,因为不允许知道 Enumerable.SelectMany 不依赖于传入序列的对象身份。例如,它可以将每个哈希码打印到控制台。

关于c# - In-Clause 在 LINQ 查询中多久计算一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34975128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com