Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group items by index? C# LINQ

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

like image 687
Jader Dias Avatar asked Aug 17 '09 21:08

Jader Dias


2 Answers

input
   .Select((value, index) => new { PairNum = index / 2, value })
   .GroupBy(pair => pair.PairNum)
   .Select(grp => grp.Select(g => g.value).ToArray())
   .ToArray()
like image 104
Ben M Avatar answered Oct 12 '22 23:10

Ben M


Probably not applicable to you, but you could use the new Zip method in C# 4.0


var input = new int[] { 0, 1, 2, 3, 4, 5 };
IEnumerable evens = input.Where((element, index) => index % 2 == 0);
IEnumerable odds = input.Where((element, index) => index % 2 == 1);
var results = evens.Zip(odds, (e, o) => new[] { e, o }).ToArray();

like image 40
Mike Two Avatar answered Oct 12 '22 22:10

Mike Two