views:

131

answers:

1

I'm building a LINQ query using a loop that appends predicates using an array:

foreach (string tag in tags)
{
    result = result.Where(p => (p.TagsDelimited).Contains("," + tag + ","));
}

This creates all the necessary clauses, but each clause compares only the last element in the tags array, producing the sql

(((',' + [t0].[TagsDelimited]) + ',') LIKE '%,taglast,%') AND (((',' + [t0].[TagsDelimited]) + ',') LIKE '%,taglast,%')

instead of one clause for each tag.

I can work around this by adding

string temp = tag;

inside the for loop and using temp instead of tag.

The question is: How is this possible!?

+1  A: 

The lambda captures the variable, not the value.

For more explanation, you might want to read my answer to this question

Mehrdad Afshari