[英]LINQ ThenBy in circle
Why I have different results in gg ? 为什么我在gg中有不同的结果?
Version: 版:
var kk = ff.OrderBy(el => el.path[0]); for (var i = 1; i <= 2; i++) { kk = kk .ThenBy(el => el.path.Length > i ? el.path[i] : 0); } var gg = kk.ToList();
Version: 版:
var kk = ff.OrderBy(el => el.path[0]); kk = kk .ThenBy(el => el.path.Length > 1 ? el.path[1] : 0) .ThenBy(el => el.path.Length > 2 ? el.path[2] : 0); var gg = kk.ToList();
I need result by Version 2, but i need in cycle 我需要版本2的结果,但我需要循环
This is because any variable that is declared outside a lambda expression is not captured inside the lambda ie you don't create multiple versions of i
in each of the lambdas. 这是因为在lambda表达式外部声明的任何变量都不会在lambda内部捕获,即,您不会在每个lambda中创建
i
多个版本。
For example, 例如,
List<Action> actions = new List<Action>();
for (int i = 0 ; i < 10 ; i++) {
actions.Add(() => Console.WriteLine(i));
}
actions.ForEach(x => x.Invoke());
Prints 10
10 times, instead of 0 to 9 as you would expect. 打印
10
10次,而不是您期望的0到9。 The same thing happens in your code. 同样的事情发生在您的代码中。 Your first code snippet is equivalent to this:
您的第一个代码段与此等效:
kk = kk
.ThenBy(el => el.path.Length > 1
? el.path[3]
: 0)
.ThenBy(el => el.path.Length > 2
? el.path[3]
: 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.