Split List into Sublists with LINQ

前端 未结 30 2382
灰色年华
灰色年华 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 06:53

    completely lazy, no counting or copying:

    public static class EnumerableExtensions
    {
    
      public static IEnumerable> Split(this IEnumerable source, int len)
      {
         if (len == 0)
            throw new ArgumentNullException();
    
         var enumer = source.GetEnumerator();
         while (enumer.MoveNext())
         {
            yield return Take(enumer.Current, enumer, len);
         }
      }
    
      private static IEnumerable Take(T head, IEnumerator tail, int len)
      {
         while (true)
         {
            yield return head;
            if (--len == 0)
               break;
            if (tail.MoveNext())
               head = tail.Current;
            else
               break;
         }
      }
    }
    

提交回复
热议问题