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
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
input
.Select((value, index) => new { PairNum = index / 2, value })
.GroupBy(pair => pair.PairNum)
.Select(grp => grp.Select(g => g.value).ToArray())
.ToArray()
var indexedNumbers = input.Select((number, index) => new { Index = index, Number = number });
var pairs =
from indexedNumber in indexedNumbers
group indexedNumber by indexedNumber.Index / 2 into indexedNumberPair
select indexedNumberPair.Select(indexedNumber => indexedNumber.Number);
var arrays = pairs.Select(pair => pair.ToArray()).ToArray();
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();