Search code examples
c#iteratorenumerableyield-return

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.


Solution

  • 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;
    }