问题
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,
回答1:
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).
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/731337/adding-a-parameter-to-a-findall-for-a-generic-list-in-c-sharp