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

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<string> keys = FillKeys()
foreach (string key in keys){
    string copy = key;
    q = q.Where(c => c.Company.Name.Contains(copy));
}

Leave a Comment