I have a generic method which adds all the html controls I have on a page into a generic list using a series of foreach loops which works. Is it possible to convert this into a LINQ expression?
private List<T> GetControls<T>() where T : HtmlControl
{
List<T> c = new List<T>();
foreach (HtmlControl c1 in Controls)
{
foreach (HtmlControl c2 in c1.Controls)
{
if (c2.GetType() == typeof(HtmlForm))
{
foreach (Control c3 in c2.Controls)
{
if (c3.GetType() == typeof(ContentPlaceHolder))
{
foreach (HtmlControl c4 in c3.Controls)
{
if (c4.GetType() == typeof(T))
{
c.Add((T)c4);
}
if (c4.GetType() == typeof(PlaceHolder))
{
foreach (HtmlControl c5 in c4.Controls)
{
if (c5.GetType() == typeof(T))
{
c.Add((T)c5);
}
}
}
}
}
}
}
}
}
return c;
}
This should do it:
However note I’ve used
isinstead of a type comparison here. This is deliberate, because this is what theOfTypeLINQ method also uses internally.If you’re sure you want exact types rather than objects that pass an
iscomparison, you’ll have to implement your ownOfType(or just use.Where(x => x.GetType == typeof(whatever))instead.)(Also note that I’ve used
Controlinstead ofHtmlControl, in case some of yourHtmlControls contain regularControls.)