Closed
Description
Sometimes, you need to handle the elements of a collection differently, based on whether they satisfy a predicate or not.
To do this, you could just perform a Where
operation on the source collection to get the elements that satisfy the predicate, and another Where
to get the elements that don't satisfy the predicate.
This, however, requires multiple enumerations of the source collection, and writing the predicate twice, with and without a not
operator.
I'd propose a new operator SplitBy
that does this.
public static PredicatedCollections<T> SplitBy<T>(this IEnumerable<T> source, Predicate<T> predicate)
Returning a strongly-typed object with the two collections:
public class PredicatedCollections<T>
{
public IEnumerable<T> SatisfiedCollection { get; }
public IEnumerable<T> UnsatisfiedCollection { get; }
}
The result could be calculated eagerly (returning IList
s) or lazily.
Example
var numbers = new [] { -10, 5, -1, 3 };
var result = numbers.SplitBy(n => n >= 0);
var positives = result.SatisfiedCollection; // [5, 3]
var negatives = result.UnsatisfiedCollection; // [-10, -1]