Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# combine yield return of multiple functions

c# yield compute will delay execution of each iteration of a loop only when that particular enumerated element is actually needed by the caller. Is it possible to combine multiple such yield return functions and still expose a dynamically enumerated set to the ultimate caller ?

public IEnumerable<string> GetDelayedCompute1()
{
    // compute ...
    foreach(var s in results)
    {
        yield return s;
    }
}

public IEnumerable<string> GetDelayedCompute2()
{
    // compute ... 
    foreach(var s in results)
    {
        yield return s;
    }
}

public IEnumerable<string> GetResults()
{
    // how to combine results of GetDelayedCompute1 and GetDelayedCompute2
    // and yield return without forcing enumeration
}
like image 905
BaltoStar Avatar asked Oct 19 '25 02:10

BaltoStar


2 Answers

The results of a LINQ operation are lazy-evaluated, so you can just:

public IEnumerable<string> GetResults()
{
    return GetDelayedCompute1().Concat(GetDelayedCompute2());
}

The results are not actually materialized until you enumerate the result of GetResults().

like image 84
John Wu Avatar answered Oct 21 '25 17:10

John Wu


Is it possible to combine multiple such yield return functions

Yes, just continue the mechanism of yield returns by foreaching over each of the methods.

foreach (var str in GetDelayedCompute1())
    yield return str;

foreach (var str in GetDelayedCompute2())
    yield return str;

Otherwise Union the result and return

 return GetDelayedCompute1().Union(GetDelayedCompute2());
like image 32
ΩmegaMan Avatar answered Oct 21 '25 17:10

ΩmegaMan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!