如何按索引对项目进行分组? C#LINQ

时间:2009-08-17 21:06:04

标签: c# .net linq ienumerable grouping

假设我有

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

如何将它们分组成对?

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

最好使用LINQ

5 个答案:

答案 0 :(得分:31)

input
   .Select((value, index) => new { PairNum = index / 2, value })
   .GroupBy(pair => pair.PairNum)
   .Select(grp => grp.Select(g => g.value).ToArray())
   .ToArray()

答案 1 :(得分:4)

style.css

答案 2 :(得分:3)

可能不适用于您,但您可以在C#4.0中使用新的Zip方法


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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

使用ToLookup方法:

input
    .Select((number, index) => new { index , number})
    .ToLookup(_ => _.index / 2, _ => _.number)
    .Select(_ => _.ToArray())
    .ToArray();

使用Zip方法:

input
    .Zip(input.Skip(1), (_, __) => new[] {_, __})
    .Where((_, index) => index % 2 == 0)
    .ToArray();