Yield Return Many?

后端 未结 6 675
粉色の甜心
粉色の甜心 2020-12-03 04:08

I find myself foreach-ing over IEnumerables a lot just so that I can return each result. Is there a way to compress something like this

foreach (var subSelec         


        
6条回答
  •  無奈伤痛
    2020-12-03 04:57

    This is a somewhat frequently requested feature that C# does not support. See this Connect item for details:

    http://connect.microsoft.com/VisualStudio/feedback/details/256934/yield-return-to-also-yield-collections

    The proposed syntax is usually something like:

    public static IEnumerable PreorderTraversal(this BinaryTree root)
    {
        if (root == null) yield break;
        yield return root.Item;
        yield foreach root.Left.PreorderTraversal();
        yield foreach root.Right.PreorderTraversal();
    }
    

    If you are interested in playing with a C#-like language that supports this feature, take a look at Cω:

    http://research.microsoft.com/en-us/um/cambridge/projects/comega/

    You might also want to read this paper on the feature by the implementors of Cω:

    http://research.microsoft.com/en-us/projects/specsharp/iterators.pdf

    If you're interested in a non-C#-like language that supports this feature, take a look at the "yield!" feature of F#. (I just love that the name of the feature is "yield!")

    Even if you are not interested in the theoretical stuff, it sounds like you face this situation as a practical problem. You should also read Wes Dyer's article on techniques for efficiently doing this sort of nested iteration without "yield foreach":

    http://blogs.msdn.com/b/wesdyer/archive/2007/03/23/all-about-iterators.aspx

提交回复
热议问题