假设我有
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
假设我有
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
input
.Select((value, index) => new { PairNum = index / 2, value })
.GroupBy(pair => pair.PairNum)
.Select(grp => grp.Select(g => g.value).ToArray())
.ToArray()
var input = new int[] { 0, 1, 2, 3, 4, 5 };
int i = 0;
var output = input.GroupBy(item => i++ / 2);
可能并不适用于你,但你可以在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();
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();
使用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();