How to update a global variable inside `where` clause in LINQ?

佐手、 提交于 2021-02-17 06:53:07

问题


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

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?


回答1:


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.

The foreach causes the where to execute and sets your flag.

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.




回答2:


Just call ToArray() or ToList() to actually execute the code that sets the flag:

var newList = list.Where(item =>
{
    flag = true;
    return item == "2";
}).ToArray();

The predicate that you pass to the Where method is not evaluated until the list is actually enumerated.



来源:https://stackoverflow.com/questions/55868254/how-to-update-a-global-variable-inside-where-clause-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!