ControlCollection extension method optimization
- by Johan Leino
Hi, got question regarding an extension method that I have written that looks like this:
public static IEnumerable<T> FindControlsOfType<T>(this ControlCollection instance) where T : class
{
T control;
foreach (Control ctrl in instance)
{
if ((control = ctrl as T) != null)
{
yield return control;
}
foreach (T child in FindControlsOfType<T>(ctrl.Controls))
{
yield return child;
}
}
}
public static IEnumerable<T> FindControlsOfType<T>(this ControlCollection instance, Func<T, bool> match) where T : class
{
return FindControlsOfType<T>(instance).Where(match);
}
The idea here is to find all controls that match a specifc criteria (hence the Func<..) in the controls collection. My question is:
Does the second method (that has the Func) first call the first method to find all the controls of type T and then performs the where condition or does the "runtime" optimize the call to perform the where condition on the "whole" enumeration (if you get what I mean).
secondly, are there any other optimizations that I can do to the code to perform better.
An example can look like this:
var checkbox = this.Controls.FindControlsOfType<MyCustomCheckBox>(
ctrl => ctrl.CustomProperty == "Test"
)
.FirstOrDefault();