Split List into Sublists with LINQ

前端 未结 30 2392
灰色年华
灰色年华 2020-11-21 06:26

Is there any way I can separate a List into several separate lists of SomeObject, using the item index as the delimiter of each s

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 07:04

    Can work with infinite generators:

    a.Zip(a.Skip(1), (x, y) => Enumerable.Repeat(x, 1).Concat(Enumerable.Repeat(y, 1)))
     .Zip(a.Skip(2), (xy, z) => xy.Concat(Enumerable.Repeat(z, 1)))
     .Where((x, i) => i % 3 == 0)
    

    Demo code: https://ideone.com/GKmL7M

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public class Test
    {
      private static void DoIt(IEnumerable a)
      {
        Console.WriteLine(String.Join(" ", a));
    
        foreach (var x in a.Zip(a.Skip(1), (x, y) => Enumerable.Repeat(x, 1).Concat(Enumerable.Repeat(y, 1))).Zip(a.Skip(2), (xy, z) => xy.Concat(Enumerable.Repeat(z, 1))).Where((x, i) => i % 3 == 0))
          Console.WriteLine(String.Join(" ", x));
    
        Console.WriteLine();
      }
    
      public static void Main()
      {
        DoIt(new int[] {1});
        DoIt(new int[] {1, 2});
        DoIt(new int[] {1, 2, 3});
        DoIt(new int[] {1, 2, 3, 4});
        DoIt(new int[] {1, 2, 3, 4, 5});
        DoIt(new int[] {1, 2, 3, 4, 5, 6});
      }
    }
    
    1
    
    1 2
    
    1 2 3
    1 2 3
    
    1 2 3 4
    1 2 3
    
    1 2 3 4 5
    1 2 3
    
    1 2 3 4 5 6
    1 2 3
    4 5 6
    

    But actually I would prefer to write corresponding method without linq.

提交回复
热议问题