Sunday, April 17, 2011

Vexing linq to sql predicate building in a for loop

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!?

From stackoverflow
  • The lambda captures the variable, not the value.

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

0 comments:

Post a Comment