multiple keywords contains search

Mar 22, 2011 at 6:38 AM

foreach (string t in tokens)
{
    string token = t;
   expressions.Add(x => ((string)x["Title"]).Contains(token));
}

in the documentation the above is given for adding multiple keyoword to the search expressions.

I have tried the following code and

foreach (string t in tokens)
{
   expressions.Add(x => ((string)x["Title"]).Contains(token));
}
found out that only the last of the keywords gets repeated in every contains query.. The reason i understand is that linq resolves queries on demand that is why the last string pool reference is maintained and added to the query when the linq is dynamically resolved.

But the same process is going to happen for code given in documentation , since the "string token" reference is gonna remain the same and its value would be the last item in the tokens list.. But to my surprise, the code documented works and my version fails(it searches only for the last item in the tokens list). somebody please explain what is happening.

Developer
Mar 22, 2011 at 3:15 PM

Yes,

foreach (string t in tokens)
{
    string token = t;
   expressions.Add(x => ((string)x["Title"]).Contains(token));
}

should work because the lambda on certain iteration "catches" variable named "token" - and the scope of this variable is terminated after the iteration is finished.

So on next iteration, the variable named "token" differs from the variable named "token" on previous iteration - differs in the eyes of the compiler.

And

foreach (string t in tokens)
{
   expressions.Add(x => ((string)x["Title"]).Contains(t));
}
should NOT work because all lambdas on all iteration "catch" the only variable named "t" which scope is the whole loop, not a single iteration.

Hope it helps.