Can I split an IEnumerable into two by a boolean criteria without two queries?

前端 未结 3 829
再見小時候
再見小時候 2020-12-01 02:19

Can I split an IEnumerable into two IEnumerable using LINQ and only a single query/LINQ statement?

I want to avoid iter

3条回答
  •  星月不相逢
    2020-12-01 03:10

    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);
    

提交回复
热议问题