How to handle an “infinite” IEnumerable?

前端 未结 5 1698
醉梦人生
醉梦人生 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:54

    You would have to avoid any greedy functions that attempt to read to end. This would include Enumerable extensions like: Count, ToArray/ToList, and aggregates Avg/Min/Max, etc.

    There's nothing wrong with infinite lazy lists, but you must make conscious decisions about how to handle them.

    Use Take to limit the impact of an endless loop by setting an upper bound even if you don't need them all.

提交回复
热议问题