C#: yield return range/collection
Solution 1:
No, there isn't I'm afraid. F# does support this with yield!
, but there's no equivalent in C# - you have to use the loop, basically. Sorry... I feel your pain. I mentioned it in one of my Edulinq blog posts, where it would have made things simpler.
Note that using yield return recursively can be expensive - see Wes Dyer's post on iterators for more information (and mentioning a "yield foreach" which was under consideration four years ago...)
Solution 2:
If you already have an IEnumerable
to loop over, and the return type is IEnumerable
(as is the case for functions that could use yield return
), you can simply return that enumeration.
If you have cases where you need to combine results from multiple IEnumerable
s, you can use the IEnumerable<T>.Concat
extension method.
In your recursive example, though, you need to terminate the enumeration/concatenation based on the contents of the enumeration. I don't think my method will support this.