Home > other >  How do I remove all elements that match a condition and stop once that condition is not satisfied?
How do I remove all elements that match a condition and stop once that condition is not satisfied?

Time:12-18

I have a list that contains the following values: 0, 1, 1, 0, 10, 12, 13, 12, 12, 0, 1, 0, 1, 1

The output should be: 10, 12, 13, 12, 12, 0, 1, 0, 1, 1

I want to remove, starting at the beginning of the list, elements that have a value less than 2, but stop removing elements once I've reached a value that is 2 or higher. This means that all elements before "10" will be removed, but the "0" after the "12", along with all proceeding elements, will remain in the output.

Is there a LINQ method to help me do this?

CodePudding user response:

LINQ has a SkipWhile for doing this.

Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.

List<int> input = new List<int> { 0, 1, 1, 0, 10, 12, 13, 12, 12, 0, 1, 0, 1, 1 };
IEnumerable<int> output = input.SkipWhile(x => x < 2);

Console.WriteLine(string.Join(",", output));
// prints "10,12,13,12,12,0,1,0,1,1"

SkipWhile works by creating a new IEnumerable from your input and excluding elements that satisfy the condition (the value is less than 2). However, once an element is found that does not satisfy the condition (the value is 2 or higher), it will pass through all remaining elements from the source, even if subsequent values are themselves less than 2.

  • Related