Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Linq to select a range of members in a list

Tags:

c#

linq

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.

like image 972
Clinton Pierce Avatar asked Mar 08 '10 18:03

Clinton Pierce


1 Answers

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.

like image 118
Erik van Brakel Avatar answered Oct 26 '22 19:10

Erik van Brakel