Our project is currently using 2 ways to find a Control inside of pages.
The first is to use .FindControl recursively.
The other is to use LINQ like this:
(from n in Page.Controls.Cast<Control>().Descendants(c => c.Controls.Cast<Control>())
where (n as Label != null && n.ID == "TaskIDLabel")
select n).First() as Label;
Which uses this Extension:
static public IEnumerable<T> Descendants<T>(this IEnumerable<T> source,
Func<T, IEnumerable<T>> DescendBy)
{
foreach (T value in source)
{
yield return value;
foreach (T child in DescendBy(value).Descendants<T>(DescendBy))
{
yield return child;
}
}
}
Which of these 2 methods is better? Which is faster?
Your code and
FindControlare functionally different. They do not do the same thing.FindControldoes not perform a deep search, whereas your code does. From MSDN:Which is better? It depends. If you don’t know where on the page a control is, then your recursive methods can find it.
However, assume that you have two controls in a Panel (ID=”MyPanel”): a custom UserControl (ID=”MyControl”) and a Label (ID=”MyName”). If you call `MyPanel.FindControl(“MyName”), you will get back the expected label in the panel. If you use your function, it will first search within MyControl for a Label with ID=”MyName”. Because of that, if MyControl happens to also contain a label with ID=”MyName”, it will be returned instead. This could be unexpected if a control happens to generate a child control with the same ID as what you are looking for.
As for performance, your method performs a deeper search so it has the potential to be a much more expensive operation.