Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I activate another Enumerator inside the first one

I have two separate actions that are enumerators.

One can be run independently, the other depends on the first to run afterwards.

I though I would be really smart by doing this:

public IEnumerator<IResult> DoStuffIndependently()
{
   yield return this;
   yield return that;
}

public IEnumerator<IResult> DoStuffBeforeSometimes()
{
   yield return AffectThis;
   yield return AffectThat;

   yield return DoStuffIndependently();
}

This doesn't work, also putting it through a foreach doesn't work either. I don't want to step through everything myself and I'm guessing there is a really easy way to do this.

like image 333
Ingó Vals Avatar asked Feb 20 '23 20:02

Ingó Vals


2 Answers

A method is either an iterator block (yield return etc), xor a regular method (return etc). It cannot be both. As such, to use another iterator, you must iterate it - i.e.

yield return AffectThis;
yield return AffectThat;
using(var iter = DoStuffIndependently()) {
    while(iter.MoveNext()) yield return iter.Current;
}

Alternatively, you could perhaps use Concat to stitch together two existing iterators.

like image 171
Marc Gravell Avatar answered Feb 22 '23 09:02

Marc Gravell


If you want it to be IEnumerator and not IEnumerable, you'll have to iterate through it manually:

public IEnumerator<IResult> DoStuffIndependently() {
    yield return this;
    yield return that;
}

public IEnumerator<IResult> DoStuffBeforeSometimes() {
    yield return AffectThis;
    yield return AffectThat;

    var dsi = DoStuffIndependently();
    while (dsi.MoveNext()) yield return dsi.Current;
}
like image 39
user1096188 Avatar answered Feb 22 '23 09:02

user1096188