Can I split an IEnumerable into two IEnumerable using LINQ and only a single query/LINQ statement?
I want to avoid iter
Copy pasta extension method for your convenience.
public static void Fork(
this IEnumerable source,
Func pred,
out IEnumerable matches,
out IEnumerable nonMatches)
{
var groupedByMatching = source.ToLookup(pred);
matches = groupedByMatching[true];
nonMatches = groupedByMatching[false];
}
Or using tuples in C# 7.0
public static (IEnumerable matches, IEnumerable nonMatches) Fork(
this IEnumerable source,
Func pred)
{
var groupedByMatching = source.ToLookup(pred);
return (groupedByMatching[true], groupedByMatching[false]);
}
// Ex.
var numbers = new [] { 1, 2, 3, 4, 5, 6, 7, 8 };
var (numbersLessThanEqualFour, numbersMoreThanFour) = numbers.Fork(x => x <= 4);