Adding a parameter to a FindAll for a Generic List in C#

user26901 picture user26901 · Apr 8, 2009 · Viewed 7.9k times · Source

I have a list of objects that I want to filter by an integer parameter

List<testObject> objectList = new List<testObject>();

// populate objectList with testObjects

objectList.FindAll(GroupLevel0);

private static bool GroupLevel0(testObject item)
{ return item._groupLevel == 0; }

private class testObject
{
     public string _FieldSQL = null;
     public int _groupLevel;
}

What I'm looking to do is to make GroupLevel0 take in an integer as a parameter instead of hardcoding to 0. I'm working in .NET 2.0 so lambda expressions are a no-go. Is it even possible to pass a parameter into a predicate?

Thank you,

Answer

Jon Skeet picture Jon Skeet · Apr 8, 2009

If you're stuck with C# 2.0, use an anonymous method - just a slightly clunkier lambda expression (ignoring expression trees):

List<testObject> objectList = new List<testObject>();
int desiredGroupLevel = 10;

objectList.FindAll(delegate (testObject item)
{
    return item._groupLevel == desiredGroupLevel;
});

Or you could still use a method call to start with:

List<testObject> objectList = new List<testObject>();
int desiredGroupLevel = 10;

objectList.FindAll(CheckGroupLevel(desiredGroupLevel));

...

public Predicate<testItem> CheckGroupLevel(int level)
{
    return delegate (testItem item)
    {
        return item._groupLevel == level;
    };
}

If you're using Visual Studio 2008 but targeting .NET 2.0, however, you can still use a lambda expression. It's just a compiler trick which requires no framework support (again, ignoring expression trees).