Manually increment an enumerator inside foreach loop

前端 未结 8 1105
情话喂你
情话喂你 2021-01-18 06:20

I have a nested while loop inside a foreach loop where I would like to advance the enumerator indefinitately while a certain condition is met. To do this I try casting the e

8条回答
  •  既然无缘
    2021-01-18 07:09

    One alternative not yet mentioned is to have an enumerator return a wrapper object which allows access to itself in addition to the data element being enumerated. For sample:

    struct ControllableEnumeratorItem
    {
      private ControllableEnumerator parent;
      public T Value {get {return parent.Value;}}
      public bool MoveNext() {return parent.MoveNext();}
      public ControllableEnumeratorItem(ControllableEnumerator newParent)
        {parent = newParent;}
    }
    

    This approach could also be used by data structures that want to allow collections to be modified in controlled fashion during enumeration (e.g. by including "DeleteCurrentItem", "AddBeforeCurrentItem", and "AddAfterCurrentItem" methods).

提交回复
热议问题