如何在LINQ的`where`子句中更新全局变量? [英] How to update a global variable inside `where` clause in LINQ?
问题描述
我想使用 LINQ
和 Where
扩展方法来过滤列表.但是除了过滤之外,我还想更新 Where
中的全局变量.但是我做不到.考虑以下示例:
I want to filter a list using LINQ
with Where
extension method. But apart from filtering I also want to update a global variable inside Where
. However I cannot do it. Consider this example:
var list = new List<string> { "1", "2", "3", "4", "5" };
bool flag = false;
var newList = list.Where(item =>
{
flag = true;
return item == "2";
});
// Here I expect flag = true, but in fact it's false
Console.Write(flag);
如您所见,我将 flag = true
设置为,执行后仍将值 flag == false
设置为
.这对我来说没有意义.您能解释一下幕后发生的事情以及为什么 flag
不变的原因.还有没有办法完全更改 LINQ
内部的全局变量?
As you can see I set flag = true
, still the value flag == false
after execution. It does not make sense to me. Can you explain what is going on under the hood and why flag
is not changed. Also is there a way to change global variables inside LINQ
at all?
推荐答案
Linq查询是惰性的,因此在枚举newList之前,您将看不到更改,因为您的位置尚未执行.
Linq queries are lazy, so until you enumerate newList you will not see a change, because your where has not been executed.
var list = new List<string> { "1", "2", "3", "4", "5" };
bool flag = false;
var newList = list.Where(item =>
{
flag = true;
return item == "2";
});
Console.WriteLine(flag); // Flag is still false.
foreach (var item in newList) {
// It doesn't matter what we do here, just that we enumerate the list.
}
Console.Write(flag); // Flag is now true.
foreach导致执行位置并设置标志.
The foreach causes the where to execute and sets your flag.
我真的建议您不要使用where谓词来产生副作用,但这是您要这样做的方式.
I would really advise against using the where predicate to create a side effect, by the way, but this is how you'd do it.
这篇关于如何在LINQ的`where`子句中更新全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!