Adding a parameter to FindAll for a shared list in C #

I have a list of objects that I want to filter using 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 want to do is get GroupLevel0 to take an integer as a parameter instead of hardcoding by 0. I work in .NET 2.0, so lambda expressions are not-go. Is it even possible to pass a parameter to a predicate?

Thanks,

+5
source share
3 answers

If you're stuck with C # 2.0, use an anonymous method - just 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 can still use the method call to start:

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;
    };
}

, Visual Studio 2008, .NET 2.0, . , ( , ).

+7
  int groupLevel = 0;

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

, , "groupLevel".

# 2.0 . , .NET 3.5 .

+2
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 are using VS 2008, you can use lambdas when compiling to 2.0. It uses a 3.5 compiler with a target value of 2.0, and we have been using it for several months.

0
source

All Articles