Using Linq to select a range of members in a list

c#, linq

Solution

Take a look at the TakeWhile Linq extension method. Takes items from the list as long as the condition is true, skips the rest.

Example:

int[] ia = new int[] { -4, 10, 11, 12, 13, -1, 9, 8, 7, 6, 5, 4, -2, 
                        6, 15, 32, -5, 6, 19, 22 };

var result = ia
             .SkipWhile(i => i != -1)
             .Skip(1)
             .TakeWhile(i => i >= 0);

Note the Skip(1) after the SkipWhile. SkipWhile skips everything up to, but not including the matching element. TakeWhile then Takes items, up to but not including the matching element. Because -1 is not greater than or equal to zero, you get an empty result.

Problem

Given a list of elements like so: ``` int[] ia = new int[] { -4, 10, 11, 12, 13, -1, 9, 8, 7, 6, 5, 4, -2, 6, 15, 32, -5, 6, 19, 22 }; ``` Is there an easy way in Linq to do something along the lines of "Select the elements from the -1 up to the next negative number (or the list exhausts)"? A successful result for -1 would be (-1, 9, 8, 7, 6, 5, 4). Using -2 would give the result (-2, 6, 15, 32). Not a homework problem. I'm just looking at an implementation using a `bool`, a `for` loop, and an `if` wondering if there's a cleaner way to do it.

Original source