Get next N elements from enumerable

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

    I think the use of Slice() would be a bit misleading. I think of that as a means to give me a chuck of an array into a new array and not causing side effects. In this scenario you would actually move the enumerable forward 10.

    A possible better approach is to just use the Linq extension Take(). I don't think you would need to use Skip() with a generator.

    Edit: Dang, I have been trying to test this behavior with the following code

    Note: this is wasn't really correct, I leave it here so others don't fall into the same mistake.

    var numbers = RandomNumberGenerator();
    var slice = numbers.Take(10);
    
    public static IEnumerable RandomNumberGenerator()
    {
        yield return random.Next();
    }
    

    but the Count() for slice is alway 1. I also tried running it through a foreach loop since I know that the Linq extensions are generally lazily evaluated and it only looped once. I eventually did the code below instead of the Take() and it works:

    public static IEnumerable Slice(this IEnumerable enumerable, int size)
    {
        var list = new List();
        foreach (var count in Enumerable.Range(0, size)) list.Add(enumerable.First());
        return list;
    }
    

    If you notice I am adding the First() to the list each time, but since the enumerable that is being passed in is the generator from RandomNumberGenerator() the result is different every time.

    So again with a generator using Skip() is not needed since the result will be different. Looping over an IEnumerable is not always side effect free.

    Edit: I'll leave the last edit just so no one falls into the same mistake, but it worked fine for me just doing this:

    var numbers = RandomNumberGenerator();
    
    var slice1 = numbers.Take(10);
    var slice2 = numbers.Take(10);
    

    The two slices were different.

提交回复
热议问题