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

若如初见. 提交于 2019-12-05 08:27:06

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

  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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!