I wanted to be able to select sequential elements from a list based on a specified predicate. I needed to be able to include or exclude the begin and end elements as well. Here is how I made use of Linqs skipWhile and takeWhile extensions to do this:
Selecting matching elements, including the start and end points:
var matchingObjects = container.ListObjects() .SkipWhile(s => !s.Key.Equals(startingObject.Key)) .TakeWhile(s => !s.Key.Equals(endingObject.Key)) .ToList(); //now find the end point and include it matchingObjects.AddRange(container.ListObjects() .SkipWhile(s => !s.Key.Equals(endingObject.Key)).Take(1) .ToList()); return matchingObjects;
Selecting matching elements, not including the start and end points:
container.ListObjects() .SkipWhile(s => !s.Key.Equals(startingObject.Key)).Skip(1) .TakeWhile(s => !s.Key.Equals(endingObject.Key)).ToList();
I was having some trouble achieving the including end points version with one line, so I resorted to adding the last item as a separate call. I am sure there is a more elegant way to do this, so any feedback there is welcome from you Linq gurus :)
thanks,
Brent
Leave A Comment