LINQ是否原生支持将集合一分为二? [英] Does LINQ natively support splitting a collection in two?

查看:42
本文介绍了LINQ是否原生支持将集合一分为二?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出项目集合,如何基于谓词将集合分为2个子集合?

Given a collection of items, how do I split the collection into 2 sub-collections based on a predicate?

您可以在2个位置进行搜索,但是运行时间为2 * N(虽然仍为O(n),但需要两倍的时间,显然不受欢迎)

You could do 2 Where searches, but then the run time is 2*N (which, while still O(n), takes twice as long and is obviously not preferred)

IEnumerable<int> even = nums.Where(i => IsEven(i));
IEnumerable<int> odd = nums.Where(i => !IsEven(i));

您可以自己进行一次线性传递(在此将其重构为扩展方法),但这意味着您必须将这些代码全部拖动,更多的自定义代码会使事情变得难以维护.

You could do a single linear pass yourself (refactored into an extension method here), but this means you have to drag this code all over, and more custom code makes things less maintainable.

public static void SplitOnPred<T>(
        this IEnumerable<T> collection,
        Func<T, bool> pred,
        out IEnumerable<T> trueSet,
        out IEnumerable<T> falseSet
    ) {
        List<T> trueSetList = new List<T>();
        List<T> falseSetList = new List<T>();
        foreach( T item in collection ) {
            if( pred( item ) ) {
                trueSetList.Add( item );
            } else {
                falseSetList.Add( item );
            }
        }
        trueSet = trueSetList;
        falseSet = falseSetList;
}

问题:LINQ是否有任何本机支持以1次线性传递方式拆分集合?

Question: Does LINQ have any native support for splitting a collection in 1 linear pass?

推荐答案

LINQ是否有本机支持以1次线性传递方式拆分集合?

Does LINQ have any native support for splitting a collection in 1 linear pass?

没有内置方法可基于谓词将集合分为两个版本.您将需要使用自己的方法,类似于您发布的方法.

There are no built-in methods that split a collection into two versions based on a predicate. You would need to use your own method, similar to the one you posted.

最接近的内置方法是 GroupBy (或 ToLookup > ).您可以按奇数或偶数分组:

The closest built-in method would be GroupBy (or ToLookup). You could group by odd or even:

var groups = nums.GroupBy(i => IsEven(i));

根据数字是奇数还是偶数,这将分为两个组".

This will split into two "groups" based on whether the numbers are odd or even.

这篇关于LINQ是否原生支持将集合一分为二?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆