ControlCollection extension method optimization

Posted by Johan Leino on Stack Overflow See other posts from Stack Overflow or by Johan Leino
Published on 2010-04-23T08:21:31Z Indexed on 2010/04/23 8:33 UTC
Read the original article Hit count: 217

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();

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about extension-methods