使用LINQ将列表拆分为子列表 [英] Split List into Sublists with LINQ

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

问题描述

有什么办法可以将列表< SomeObject> 分成几个单独的 SomeObject 列表,使用项目索引作为每个拆分的分隔符?

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

让我举例说明:

我有一个列表< SomeObject> ,我需要一个列表< SomeObject> 列表< SomeObject& ] ,以便每个这些结果列表将包含一组原始列表的3个项目(顺序)。

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.

推荐答案

尝试以下代码。

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 列表列表 列表 s

The idea is to first group the elements by indexes. Dividing by three has the effect of grouping them into groups of 3. Then convert each group to a list and the IEnumerable of List to a List of Lists

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

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