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
}
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()
.
Is it possible to combine multiple such yield return functions
Yes, just continue the mechanism of yield returns
by foreach
ing 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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With