使用 LINQ 将列表拆分为子列表 [英] Split List into Sublists with LINQ
问题描述
有什么办法可以将一个List
分成几个单独的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?
举个例子:
我有一个 List
并且我需要一个 List
或 >
List
,这样每个结果列表都将包含原始列表的一组 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组.然后将每组转换为列表,将List
的IEnumerable
转换为List
List
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 List
s
这篇关于使用 LINQ 将列表拆分为子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!