使用linq将列表<t>分解为n个长度的列表<t>?

Dis*_*ive 21 .net linq

可能重复:
如何将IEnumerable <String>拆分为IEnumerable <string>组

我有一个列表,我想分成10组.

如果我有一个对象

List<Person> allPendingPersons 
Run Code Online (Sandbox Code Playgroud)

长度为m.

在LINQ中是否有一种优雅的方法可以将allPendingPersons分解为一个或多个List对象,这些对象都有最多10个人?

SLa*_*aks 51

您可以编写自己的扩展方法:

public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> sequence, int size) {
    List<T> partition = new List<T>(size);
    foreach(var item in sequence) {
        partition.Add(item);
        if (partition.Count == size) {
            yield return partition;
            partition = new List<T>(size);
        }
    }
    if (partition.Count > 0)
        yield return partition;
}
Run Code Online (Sandbox Code Playgroud)

我在博客中更深入地探讨了这一点.


Bal*_*a R 17

 var groups = allPendingPersons.Select((p, index) => new {p,index})
                               .GroupBy(a =>a.index/10 );
Run Code Online (Sandbox Code Playgroud)

如果你想处理IGrouping<,>.如果您正在寻找List> back,您可以尝试

var listOfLists = allPendingPersons.Select((p, index) => new {p, index})
    .GroupBy(a => a.index/10)
    .Select((grp => grp.Select(g => g.p).ToList()))
    .ToList();
Run Code Online (Sandbox Code Playgroud)


Eni*_*ity 7

.NETReactive Extensions(Rx)有一个扩展方法,可以完全按照您的要求执行:

var buffered = allPendingPersons.BufferWithCount(10);
Run Code Online (Sandbox Code Playgroud)

如果你想使用LINQ,你可以这样做:

var buffered =
    allPendingPersons
        .Select((p, i) => new { Group = i / 10, Person = p })
        .GroupBy(x => x.Group, x => x.Person)
        .Select(g => g.ToArray());
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

13767 次

最近记录:

12 年,11 月 前