【问题标题】:How can I divide a collection into sub collections of 50 elements each in C#? [duplicate]如何在 C# 中将集合划分为每个包含 50 个元素的子集合? [复制]
【发布时间】:2013-12-03 06:41:00
【问题描述】:

我有一个如下所示的集合:

IList<TQBase> = hq;

public class TQBase
{
    public int i { get; set; }
    public int q { get; set; }
}

集合中有超过 300 件物品。

现在我需要创建这些集合的集合,这样:

h[0] = the first fifty elements of hq
h[1] = the next fifty elements of hq
...
h[n] = any remaining elements of hq

谁能建议我创建第二个集合的方法。这是不是 我可以使用 Linq 还是有更简单的方法?

【问题讨论】:

标签: c# linq


【解决方案1】:
List<List<TQBase>> result = new List<List<TQBase>>();

for(var i = 0; i < hq.Length; i+= 50){
   result.Add(hq.Skip(i * 50).Take(50).ToList());
}

【讨论】:

    【解决方案2】:

    使用GroupBy:

    IEnumerable<List<TQBase>> groups = hq.Select((t, index) => new{ t, index })
        .GroupBy(x => x.index / 50)
        .Select(xg => xg.Select(x => x.t).ToList());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 2012-12-01
      • 1970-01-01
      相关资源
      最近更新 更多