简体   繁体   中英

LINQ with generic Predicate constraint

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM