Get next N elements from enumerable

后端 未结 10 1514
遥遥无期
遥遥无期 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:21

    I had made some mistakes in my original answer but some of the points still stand. Skip() and Take() are not going to work the same with a generator as it would a list. Looping over an IEnumerable is not always side effect free. Anyway here is my take on getting a list of slices.

        public static IEnumerable RandomNumberGenerator()
        {
            while(true) yield return random.Next();
        }
    
        public static IEnumerable> Slice(this IEnumerable enumerable, int size, int count)
        {
            var slices = new List>();
            foreach (var iteration in Enumerable.Range(0, count)){
                var list = new List();
                list.AddRange(enumerable.Take(size));
                slices.Add(list);
            }
            return slices;
        }
    

提交回复
热议问题