views:

48

answers:

1

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();
+2  A: 

It would run your first method (the iterator) to find all the controls, yes, but it would check one value at a time. That is, it would find one control, check it using the Where clause, find the next, check it and so on. I can't really see any optimisations in the algorithm - whatever you do you have to check every control (once) and that is what you're doing.

Evgeny