Optimizing the ControlCollection Extension Method
got a question about an extension method I wrote 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 the controls that match the specificc criterion (hence Func <..>) in the controls collection. My question is:
The second method (which has a Func) first calls the first method to find all controls of type T and then does the where clause or does a "runtime" call optimization to satisfy the where clause on the "whole" enum (if you understand what I have in mind).
secondly, are there any other optimizations I can make to make the code work better.
An example might look like this:
var checkbox = this.Controls.FindControlsOfType<MyCustomCheckBox>(
ctrl => ctrl.CustomProperty == "Test"
)
.FirstOrDefault();
a source to share
It will run your first method (iterator) to find all the controls, yes, but it will check one value at a time. That is, it finds one control, checks it with a Where clause, finds the next, checks it, and so on. I don't see any optimizations in optimization - whatever you do, you need to check every control (once), and that's what you do.
a source to share