Linq query built in foreach loop always takes parameter value from last iteration

后端 未结 3 1247
说谎
说谎 2020-11-27 20:30

I have a List containing several keywords. I foreach through them building my linq query with them like so (boiled down to remove the code noise):

List

        
3条回答
  •  一生所求
    2020-11-27 20:51

    You're reusing the same variable (key) in your lambda expression.

    See my article on anonymous methods for more details, and there are a number of related SO questions too:

    • LINQ to SQL bug (or very strange feature)...
    • Local variables with delegates
    • C# captured variable in a loop
    • C# gotcha answer
    • Building a LINQ query programmatically without local variables tricking me

    The simple fix is to copy the variable first:

    List keys = FillKeys()
    foreach (string key in keys){
        string copy = key;
        q = q.Where(c => c.Company.Name.Contains(copy));
    }
    

提交回复
热议问题