使用 LINQ 将集合拆分为“n"个部分? [英] Split a collection into `n` parts with LINQ?

查看:34
本文介绍了使用 LINQ 将集合拆分为“n"个部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有使用 LINQ 将集合拆分为 n 个部分的好方法?当然不一定均匀.

Is there a nice way to split a collection into n parts with LINQ? Not necessarily evenly of course.

也就是说,我想将集合划分为子集合,每个子集合包含元素的一个子集,其中最后一个集合可以是参差不齐的.

That is, I want to divide the collection into sub-collections, which each contains a subset of the elements, where the last collection can be ragged.

推荐答案

一个纯linq,最简单的解决方案如下图.

A pure linq and the simplest solution is as shown below.

static class LinqExtensions
{
    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
    {
        int i = 0;
        var splits = from item in list
                     group item by i++ % parts into part
                     select part.AsEnumerable();
        return splits;
    }
}

这篇关于使用 LINQ 将集合拆分为“n"个部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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