How to group items by index? C# LINQ

2020-02-26 04:27发布

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

5条回答
Fickle 薄情
2楼-- · 2020-02-26 05:07
input
   .Select((value, index) => new { PairNum = index / 2, value })
   .GroupBy(pair => pair.PairNum)
   .Select(grp => grp.Select(g => g.value).ToArray())
   .ToArray()
查看更多
Deceive 欺骗
3楼-- · 2020-02-26 05:17
var input = new int[] { 0, 1, 2, 3, 4, 5 };
int i = 0;
var output = input.GroupBy(item => i++ / 2);
查看更多
SAY GOODBYE
4楼-- · 2020-02-26 05:17

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

查看更多
戒情不戒烟
5楼-- · 2020-02-26 05:18
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();
查看更多
够拽才男人
6楼-- · 2020-02-26 05:23

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();
查看更多
登录 后发表回答