Can you set/update a value in real time within a LINQ statement during iteration?

Based on a proposed answer to my other question here... is it possible to update a variable during LINQ enumeration so you can use it as part of a test?

For instance, is anything like this possible?

// Assume limitItem is of type Foo and sourceList is of type List<Foo> 

// Note the faux attempt to set limitItemFound in the TakeWhile clause
// That is what I'm wondering.

sourceList.Reverse()
    .TakeWhile(o => (o != limitItem) && !limitItemFound; limitItemFound = limitItemFound || (o == limitItem) )
    .FirstOrDefault(o => ...);

This would make the search inclusive of limitItem.

Jon Skeet
people
quotationmark

For LINQ to Objects (which takes delegates) then you can, yes - using a statement lambda:

sourceList.Reverse()
    .TakeWhile(o =>  { 
             ... fairly arbitrary code here
             return someValue;
         })
    .FirstOrDefault(o => ...);

I would strongly discourage you from doing this though. It will make it much harder to understand what's going on, because you're losing the declarative nature of idiomatic LINQ code.

people

See more on this question at Stackoverflow