views:

2396

answers:

3

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,

+6  A: 

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).

Jon Skeet
SKEET! Sniped again!
FlySwat
Scott Vercuski
+2  A: 
  int groupLevel = 0;

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

This is an anonymous delegate, it closes over the lexical scope of its parent, so it can see "groupLevel".

Works in C# 2.0 and above. I'd recommend using a lambda if you move to .NET 3.5 in the future.

FlySwat
Or even if you move to C# 3 but still .NET 2.0...
Jon Skeet
A: 
List<testObject> objectList = new List<testObject>();

// populate objectList with testObjects

objectList.FindAll(delegate(testObject o){ return GroupLevel(o, 0);} );

private static bool GroupLevel(testObject item, int groupLevel)
{ return item._groupLevel == groupLevel; }

Also, if you use VS 2008, you can still use lambdas when compiling to 2.0. It uses the 3.5 compiler with a 2.0 target, and we've been using it for months.

Chris Doggett
Why? Thats kinda silly.
FlySwat
What's kinda silly?
Chris Doggett
Your wrapping a delegate for no reason, just put the delegate code in the anonymous delegate.
FlySwat
I just edited his code to use as an example. It's by no means the most elegant.
Chris Doggett