Get next N elements from enumerable

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

    Let's see if you even need the complexity of Slice. If your random number generates is stateless, I would assume each call to it would generate unique random numbers, so perhaps this would be sufficient:

    var group1 = RandomNumberGenerator().Take(10);  
    var group2 = RandomNumberGenerator().Take(10);  
    var group3 = RandomNumberGenerator().Take(10);  
    var group4 = RandomNumberGenerator().Take(10);
    

    Each call to Take returns a new group of 10 numbers.

    Now, if your random number generator re-seeds itself with a specific value each time it's iterated, this won't work. You'll simply get the same 10 values for each group. So instead, you would use:

    var generator  = RandomNumberGenerator();
    var group1     = generator.Take(10);  
    var group2     = generator.Take(10);  
    var group3     = generator.Take(10);  
    var group4     = generator.Take(10);
    

    This maintains an instance of the generator so that you can continue retrieving values without re-seeding the generator.

提交回复
热议问题