如何通过索引组项目? C#LINQ(How to group items by index? C

2019-08-01 12:06发布

假设我有

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

Answer 1:

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


Answer 2:

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


Answer 3:

可能并不适用于你,但你可以在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();



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


Answer 5:

使用ToLookup方法:

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

使用邮编方法:

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


文章来源: How to group items by index? C# LINQ