You have List<Foo>objects, but Foohas a property IsSelectedlike this ...
public class Foo
{
public string Name{ get; set; }
public bool IsSelected{ get; set; }
}
List<Foo> sourceItems = new List<Foo>
{
new Foo(){ Name="First", IsSelected=false},
new Foo(){ Name="Second", IsSelected=true },
new Foo(){ Name="Third", IsSelected=false},
new Foo(){ Name="Fourth", IsSelected=true },
new Foo(){ Name="Fifth", IsSelected=false},
new Foo(){ Name="Sixth", IsSelected=true },
new Foo(){ Name="Seventh", IsSelected=true },
new Foo(){ Name="Eighth", IsSelected=false},
new Foo(){ Name="Ninth", IsSelected=false},
new Foo(){ Name="Tenth", IsSelected=false}
};
Using the Where clause, of course, I can only get the elements that are selected, for example ...
var results = sourceItems.Where(item => item.IsSelected);
... but what if I want all the elements between the first and last element, where IsSelected is true? (i.e., second to seventh)
I know that I can use SkipWhile, since it skips to the first true operator, and then returns everything after ...
var results = sourceItems.SkipWhile(item => !item.IsSelected);
... and I know that I can undo and do the same again, but then I would have to rediscover it at the end, and double treatment just seems like it would be unnecessarily expensive.
- Select , IsSelected , Where , , , .
int lastSelectedIndex = -1;
var results = sourceItems
.SkipWhile(item => !item.IsSelected)
.Select( (item, itemIndex) =>
{
if(item.IsSelected)
lastSelectedIndex = index;
return new {item, index};
})
.Where(anonObj => anonObj.index <= lastSelectedIndex)
.Select(anonObj => anonObj.Item);
, , Where Take , , , lastSelectedIndex , , Select , , .
.Take(lastSelectedIndex + 1);
, ?