Is there a built-in way to convert IEnumerator to IEnumerable

前端 未结 8 1786
面向向阳花
面向向阳花 2020-12-30 18:55

Is there a built-in way to convert IEnumerator to IEnumerable?

8条回答
  •  不思量自难忘°
    2020-12-30 19:00

    The easiest way of converting I can think of is via the yield statement

    public static IEnumerable ToIEnumerable(this IEnumerator enumerator) {
      while ( enumerator.MoveNext() ) {
        yield return enumerator.Current;
      }
    }
    

    compared to the list version this has the advantage of not enumerating the entire list before returning an IEnumerable. using the yield statement you'd only iterate over the items you need, whereas using the list version, you'd first iterate over all items in the list and then all the items you need.

    for a little more fun you could change it to

    public static IEnumerable Select(this IEnumerator e, 
                                             Func selector) {
          while ( e.MoveNext() ) {
            yield return selector(e.Current);
          }
        }
    

    you'd then be able to use linq on your enumerator like:

    IEnumerator enumerator;
    var someList = from item in enumerator
                   select new classThatTakesTInConstructor(item);
    

提交回复
热议问题