views:

278

answers:

1

I just upgraded my project to .NET 3.5 and thought I had a perfect use for LINQ. My application has a window manager that tracks open windows at runtime and I'm trying to add a FindOpenWindows generic method. What I've done so far:

    List<Form> openWindows;

    public List<T> FindOpenWindows<T>(Predicate<T> constraint)
    {
        var foundTs = from form in openWindows
                          where constraint(form)
                                && form.Created
                          select form;

        return foundTs as List<T>;
    }

But I get the "Delegate System.Predicate has some invalid arguments." So I rewrote the method as:

    public List<T> FindOpenWindows<T>(Predicate<Form> constraint)
    {
        var foundTs = from form in openWindows
                          where constraint(form as Form)
                                && form.Created
                          select form;

        return foundTs as List<T>;
    }

The reason I did not make the function non-generic is so that the caller gets a List of exactly the type of window they're looking for.

Since I'm new to LINQ and Lambda expressions I'm not sure exactly how to write the code for the Predicate in the call to FindOpenWindows. I obviously need to be able to verify that the Form being passed in is not null and I need to be able to check to see if it matches the type I'm looking for.

+2  A: 
public List<T> FindOpenWindows<T>(Predicate<T> constraint)
   where T : Form
{
    var foundTs = from form in openWindows
                      where constraint(form)
                            && form.Created
                      select form;

    return foundTs.ToList();
}

Try that. You need to constrain the T to be of type Form.

BFree
Thanks, that works perfectly! I was able to figure out the call should be:List<frmMain> mainWindows = Program.windowManager.FindOpenWindows<frmMain>((Form f) => f is frmMain);
jasonh