Reputation: 12192
I have a collection where each element has a property called IsTop. What I want to do is use linq (if possible) to select everything after the first occurence of IsTop == true. Right now, I do this like this:
bool[] foundTop = {false}; // use array for modified closure
foreach (var config in fullHierarchy
.Where(config => config.IsTop || foundTop[0]))
{
foundTop[0] = true;
configurationHierarchy.Add(config);
}
I feel like this is a bit contrived. Is there a simpler way to achieve this in LINQ?
Upvotes: 3
Views: 143
Reputation: 56536
I think that SkipWhile
is what you're looking for, e.g.
var myArray = new[]
{
new { IsTop = false, S = 'a' },
new { IsTop = true, S = 'b' },
new { IsTop = false, S = 'c' },
};
myArray.SkipWhile(x => !x.IsTop); // contains the elements with 'b' and 'c'
// in your code, might be
foreach (var config in fullHierarchy.SkipWhile(x => !x.IsTop))
{
configurationHierarchy.Add(config);
}
Upvotes: 4
Reputation: 63327
Try this:
var result = fullHierarchy.SkipWhile(x=>!x.IsTop).Skip(1);
Upvotes: 5
Reputation: 149030
You can use something like this:
var afterTop = fullHierarchy.SkipWhile(x => !x.IsTop).Skip(1);
The SkipWhile
skips all elements until the first item is found where IsTop == true
, then the Skip
skips that element, too. The result will be all items in fullHierarchy
after the first one where IsTop == true
.
Upvotes: 12