How to group items by index? C# LINQ

Jader Dias picture Jader Dias · Aug 17, 2009 · Viewed 12.6k times · Source

Suppose I have

var input = new int[] { 0, 1, 2, 3, 4, 5 };

How do I get them grouped into pairs?

var output = new int[][] { new int[] { 0, 1 }, new int[] { 2, 3 }, new int[] { 4, 5 } };

Preferably using LINQ

Answer

Ben M picture Ben M · Aug 17, 2009
input
   .Select((value, index) => new { PairNum = index / 2, value })
   .GroupBy(pair => pair.PairNum)
   .Select(grp => grp.Select(g => g.value).ToArray())
   .ToArray()