Thursday, February 8, 2018

c# - IEnumerable and Recursion using yield return



I have an IEnumerable method that I'm using to find controls in a WebForms page.




The method is recursive and I'm having some problems returning the type I want when the yield return is returnig the value of the recursive call.



My code looks as follows:



    public static IEnumerable 
GetDeepControlsByType(this Control control)
{
foreach(Control c in control.Controls)
{
if (c is T)

{
yield return c;
}

if(c.Controls.Count > 0)
{
yield return c.GetDeepControlsByType();
}
}
}



This currently throws a "Cannot convert expression type" error. If however this method returns type IEnumerable, the code builds, but the wrong type is returned in the output.



Is there a way of using yield return whilst also using recursion?


Answer



Inside a method that returns IEnumerable, yield return has to return T, not an IEnumerable.



Replace




yield return c.GetDeepControlsByType();


with:



foreach (var x in c.GetDeepControlsByType())
{
yield return x;
}


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...