I have an IEnumerable<T>
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<Control> GetDeepControlsByType<T>(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<T>();
}
}
}
This currently throws a "Cannot convert expression type" error. If however this method returns type IEnumerable<Object>
, the code builds, but the wrong type is returned in the output.
Is there a way of using yield return
whilst also using recursion?
if(c.Controls.Count > 0)
-->if(c.Controls.Any())
, especially if you are yielding as well:) – Kelsoyield
. Please see below :) And it's a one-liner too :) – Kelsoyield return
in recursive functions, the memory usage scales explosively. See https://mcmap.net/q/93132/-ienumerable-and-recursion-using-yield-return – Rathenau