Get next N elements from enumerable

后端 未结 10 1501
遥遥无期
遥遥无期 2020-12-16 17:38

Context: C# 3.0, .Net 3.5
Suppose I have a method that generates random numbers (forever):

private static IEnumerable RandomNumberGenerator(         


        
10条回答
  •  再見小時候
    2020-12-16 18:06

    I got this solution for the same problem:

    int[] ints = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    IEnumerable> chunks = Chunk(ints, 2, t => t.Dump());
    //won't enumerate, so won't do anything unless you force it:
    chunks.ToList();
    
    IEnumerable Chunk(IEnumerable src, int n, Func, T> action){
      IEnumerable head;
      IEnumerable tail = src;
      while (tail.Any())
      {
        head = tail.Take(n);
        tail = tail.Skip(n);
        yield return action(head);
      }
    }
    

    if you just want the chunks returned, not do anything with them, use chunks = Chunk(ints, 2, t => t). What I would really like is to have to have t=>t as default action, but I haven't found out how to do that yet.

提交回复
热议问题