How to group items by index? C# LINQ

2020-02-26 05:10发布

问题:

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

回答1:

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


回答2:

var input = new int[] { 0, 1, 2, 3, 4, 5 };
int i = 0;
var output = input.GroupBy(item => i++ / 2);


回答3:

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



回答4:

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


回答5:

Using ToLookup method:

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

Using Zip method:

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