分割清单与LINQ子列表 [英] Split List into Sublists with LINQ

查看:106
本文介绍了分割清单与LINQ子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法,我可以separe列表为SomeObject几个单独的列表,使用该项指标为每个分割的分隔符?

Is there any way I can separe a List into several separate lists of SomeObject, using the item index as the delimiter of each split?

让我举例说明:
我有一个列表< SomeObject> ,我需要一个列表<名单< SomeObject>> 列表与LT; SomeObject> [] ,使这些结果列表将包含组3项原始列表(按顺序)

Let me exemplify: I have a List<SomeObject> and I need a List<List<SomeObject>> or List<SomeObject>[], so that each of these resulting lists will contain a group of 3 items of the original list (sequentially).

例如:
最初的名单: [A,G,E,W,P,S,Q,F,X,Y,I,M,C]

致使列表: [A,G,E],[W,P,S],[Q,F,X],[Y,I,M],[C]

我还需要所产生的列表大小是这个函数的参数。

I'd also need the resulting lists size to be a parameter of this function.

是否有可能?

推荐答案

请尝试以下code。

public static IList<IList<T>> Split<T>(IList<T> source)
{
    return  source
        .Select((x, i) => new { Index = i, Value = x })
        .GroupBy(x => x.Index / 3)
        .Select(x => x.Select(v => v.Value).ToList())
        .ToList();
}

我们的想法是第一组由索引的元素。除以三有其分组为3.组然后每个组转换为列表和列表的的IEnumerable 列表 列表取值

这篇关于分割清单与LINQ子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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