How to group items by index? C# LINQ

前端 未结 5 711
离开以前
离开以前 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:35

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

提交回复
热议问题