views:

30

answers:

1

This is driving me nuts. What am I missing here. I'm using EF and if I have code like the following:

using (LexiconEntities ctx = new LexiconEntities())
{
  var query = from w in ctx.Words
        select new WordEntryDataModel
        {
          Word = w.Anagram,
          NumOfAnagrams = w.NumAnagrams.Value,
          Length = w.Length.Value,
          ...
        };

  SearchCriterion c1 = new SearchCriterion();
  SearchCriterion c2 = new SearchCriterion();

  c1.MinValue = 3; 
  c1.MaxValue = 3;

  c2.MinValue = 4;
  c2.MaxValue = 4;

  query = query.Where(w => w.Length >= c1.MinValue && w.Length <= c1.MaxValue);
  query = query.Where(w => w.NumOfAnagrams >= c2.MinValue && w.NumOfAnagrams <= c2.MaxValue);

  ...
}

And when I debug the query, I get the proper results (8 records). This also works as expected in Linqpad (which frickin' rocks).

But if I construct the search criteria as a List of criterion objects, and I dynamically add on Where() clauses by iterating over the search criteria as follows:

  foreach (SearchCriterion c in criteria.SearchCriteria)
  {
    switch (c.Type)
    {
      case SearchCriterionType.WordLength:
        query = query.Where(w => w.Length >= c.MinValue && w.Length <= c.MaxValue);
        break;
      case SearchCriterionType.NumberOfAnagrams:
        query = query.Where(w => w.NumOfAnagrams >= c.MinValue && w.NumOfAnagrams <= c.MaxValue);
        break;
      ...
      case SearchCriterionType.NumberOfVowels:
        query = query.Where(w => w.NumOfVowels >= c.MinValue && w.NumOfVowels <= c.MaxValue);
        break;
    }
  }
  ...

I get the totally different (and incorrect) results. I've debugged the switch statement and my search criteria has two properly constructed criterion objects set to correct values. There's something about the conditionally added where clauses that my query doesn't like.

What am I doing wrong?

+1  A: 

Closure. Assign c to a local variable within the loop. Also see my SO answer here

Daz Lewis
That worked thanks! I don't understand why, but cool. The concept of closure hurts my brain.
eponymous23