Say I have an IEnumerable. For example, {2,1,42,0,9,6,5,3,8}.
I need to get "runs" of items that match a predicate. For example, if my predicate was
bool isSmallerThanSix(int number){...}
I would want to get the following output: {{2,1},{0},{5,3}}
Is there a built-in function that accomplishes this?
So far I have this:
public static IEnumerable<IEnumerable<T>> GetSequences<T>(this IEnumerable<T> source,
Func<T, bool> selector) {
if (source == null || selector == null) {
yield break;
}
IEnumerable<T> rest = source.SkipWhile(obj => !selector(obj));
while (rest.Count() > 0) {
yield return rest.TakeWhile(obj => selector(obj));
rest = rest
.SkipWhile(obj => selector(obj))
.SkipWhile(obj => !selector(obj));
}
}
which seems to work, but was written by me in the middle of the night and thus inefficient fifteen ways from Tuesday. Is there a better, preferably built-in (and therefore well-tested) way?
Thank y'all so much for your time,
Ria.