Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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.

like image 795
Mark A. Donohoe Avatar asked Oct 03 '13 16:10

Mark A. Donohoe


1 Answers

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.

like image 136
Jon Skeet Avatar answered Nov 12 '22 08:11

Jon Skeet