Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a LINQ method to help me do this?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading