如何将一个集合分成C#中每个50个元素的子集合?

时间:2013-11-19 15:57:28

标签: c# linq

我有一个看起来像这样的集合:

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做或者有更简单的方法吗?

2 个答案:

答案 0 :(得分:5)

使用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());

答案 1 :(得分:3)

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());
}