1

I have a collection that looks like this:

IList<TQBase> = hq;

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

The collection has over 300 items in it.

Now I need to create a collection of these collections such that:

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

Can anyone suggest a way that I can create the second collection. Is this something that I could do with Linq or is there an easier way?

Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

5

Use 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());
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
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());
}
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170