C#: yield return range/collection

C#.NetYield

C# Problem Overview


I use the yield return keyword quite a bit, but I find it lacking when I want to add a range to the IEnumerable. Here's a quick example of what I would like to do:

IEnumerable<string> SomeRecursiveMethod()
{
    // some code 
    // ...
    yield return SomeRecursiveMethod();
}

Naturally this results in an error, which can be resolved by doing a simple loop. Is there a better way to do this? A loop feels a bit clunky.

C# Solutions


Solution 1 - C#

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 - C#

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 IEnumerables, 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.

Solution 3 - C#

The yield keyword is indeed very nice. But nesting it in a for loop will cause more glue code to be generated and executed.

If you can live with a less functional style of programming, you can pass a List around to which you append:

 void GenerateList(List<string> result)
 {

      result.Add("something")

      // more code.

      GenerateList(result);

 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndr&#233; HauptView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Merlyn Morgan-GrahamView Answer on Stackoverflow
Solution 3 - C#user180326View Answer on Stackoverflow