How to handle an “infinite” IEnumerable?

前端 未结 5 1703
醉梦人生
醉梦人生 2021-02-01 17:11

A trivial example of an \"infinite\" IEnumerable would be

IEnumerable Numbers() {
  int i=0;
  while(true) {
    yield return unchecked(i++);
  }
}
         


        
5条回答
  •  走了就别回头了
    2021-02-01 17:59

    As long as you only call lazy, un-buffered methods you should be fine. So Skip, Take, Select, etc are fine. However, Min, Count, OrderBy etc would go crazy.

    It can work, but you need to be cautious. Or inject a Take(somethingFinite) as a safety measure (or some other custom extension method that throws an exception after too much data).

    For example:

    public static IEnumerable SanityCheck(this IEnumerable data, int max) {
        int i = 0;
        foreach(T item in data) {
            if(++i >= max) throw new InvalidOperationException();
            yield return item;
        }
    }
    

提交回复
热议问题