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

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

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

8条回答
  •  猫巷女王i
    2020-12-30 19:21

    You could use the following which will kinda work.

    public class FakeEnumerable : IEnumerable {
      private IEnumerator m_enumerator;
      public FakeEnumerable(IEnumerator e) {
        m_enumerator = e;
      }
      public IEnumerator GetEnumerator() { 
        return m_enumerator;
      }
      // Rest omitted 
    }
    

    This will get you into trouble though when people expect successive calls to GetEnumerator to return different enumerators vs. the same one. But if it's a one time only use in a very constrained scenario, this could unblock you.

    I do suggest though you try and not do this because I think eventually it will come back to haunt you.

    A safer option is along the lines Jonathan suggested. You can expend the enumerator and create a List of the remaining items.

    public static List SaveRest(this IEnumerator e) {
      var list = new List();
      while ( e.MoveNext() ) {
        list.Add(e.Current);
      }
      return list;
    }
    

提交回复
热议问题