How to group items by index? C# LINQ

前端 未结 5 713
离开以前
离开以前 2020-12-29 06:22

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[][] {         


        
5条回答
  •  不思量自难忘°
    2020-12-29 06:34

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

提交回复
热议问题