A scenario where LINQ is too dynamic (answered)
By rickvdbosch
- 1 minutes read - 194 wordsThe situation I talked about in my previous post had one very big issue: LINQ sometimes just is too dynamic… 😉
The fact that I changed the value for the Ranking property for each SpecificObject that got matched, made the primary LINQ query have a different outcome. LINQ uses lazy evaluation and because of that, the contents of finalGroups and exitGroups changed every time I changed the Ranking value for one of the SpecificObjects. Each time the variable containing the outcome of the LINQ query is iterated through, the query is evaluated again. This made that the matching was all off, and I ended up with a bunch of exit groups that got matched!
To have a simple solution, I did the following. This holds the final and exit objects in a ‘static’ list in stead of a dynamic query result. This way, the SpecificObjects in the finalObjects and exitObjects lists stay the same, regardless of the changes you make to any of the SpecificObjects.
int count;int numberOfPossibilities;IEnumerable temp;List finalObjects; List exitObjects;
count = 0;finalObjects = new List();exitObjects = new List();
temp = from SpecificObject specificObject in AllSpecificObjects      orderby specificObject.Ranking      select specificObject;
foreach (SpecificObject specificObject in temp){   if (count < numberOfPossibilities)   {       finalObjects.Add(specificObject);   }   else   {       exitObjects.Add(specificObject);   }   count++;}