Search code examples
c#pythongeneratoryield-return

C# analogy for Python's yield from


If I would like to merge two generators in one

def gen1():
    for i in range(5):
        yield i

def gen2():
    for i in 'asdf':
        yield i

def gen():
    yield from gen1()
    yield from gen2()

or do some recursive generator

def gen(arg):
    if arg == 1:
        yield from gen(0)
    for i in range(10):
        yield i

in Python I'll use yield from. Is there any alternative how to do similar stuff in C#?


Solution

  • No, there is no syntax sugar for combining two iterators for yield return.

    You can either use Enumerable.Concat if you just need to iterate them in sequence or write code to iterate the sequence and yield return each element.