Get next N elements from enumerable

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

    Using Skip and Take would be a very bad idea. Calling Skip on an indexed collection may be fine, but calling it on any arbitrary IEnumerable is liable to result in enumeration over the number of elements skipped, which means that if you're calling it repeatedly you're enumerating over the sequence an order of magnitude more times than you need to be.

    Complain of "premature optimization" all you want; but that is just ridiculous.

    I think your Slice method is about as good as it gets. I was going to suggest a different approach that would provide deferred execution and obviate the intermediate array allocation, but that is a dangerous game to play (i.e., if you try something like ToList on such a resulting IEnumerable implementation, without enumerating over the inner collections, you'll end up in an endless loop).

    (I've removed what was originally here, as the OP's improvements since posting the question have since rendered my suggestions here redundant.)

提交回复
热议问题