简体   繁体   English

在C#中为通用列表的FindAll添加参数

[英]Adding a parameter to a FindAll for a Generic List in C#

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. 我要做的是让GroupLevel0接受一个整数作为参数而不是硬编码为0.我在.NET 2.0中工作,所以lambda表达式是不行的。 Is it even possible to pass a parameter into a predicate? 甚至可以将参数传递给谓词吗?

Thank you, 谢谢,

If you're stuck with C# 2.0, use an anonymous method - just a slightly clunkier lambda expression (ignoring expression trees): 如果您坚持使用C#2.0,请使用匿名方法 - 只是略微笨拙的lambda表达式(忽略表达式树):

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. 但是,如果您使用的是Visual Studio 2008但是 .NET 2.0为目标 ,则仍然可以使用lambda表达式。 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". 这是一个匿名委托,它关闭了其父级的词法范围,因此它可以看到“groupLevel”。

Works in C# 2.0 and above. 适用于C#2.0及以上版本。 I'd recommend using a lambda if you move to .NET 3.5 in the future. 如果你将来迁移到.NET 3.5,我建议使用lambda。

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. 此外,如果您使用VS 2008,则在编译为2.0时仍可以使用lambdas。 It uses the 3.5 compiler with a 2.0 target, and we've been using it for months. 它使用3.5编译器和2.0目标,我们已经使用了几个月。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM