Sinaesthetic
Sinaesthetic

Reputation: 12192

How do I select everything in a list after the first occurence of?

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

Answers (3)

Tim S.
Tim S.

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

King King
King King

Reputation: 63327

Try this:

var result = fullHierarchy.SkipWhile(x=>!x.IsTop).Skip(1);

Upvotes: 5

p.s.w.g
p.s.w.g

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

Related Questions