在C#中添加参数为为的FindAll泛型列表 [英] Adding a parameter to a FindAll for a Generic List in C#

查看:104
本文介绍了在C#中添加参数为为的FindAll泛型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的列表,我想通过一个整数参数来筛选

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



什么我希望做的是使GroupLevel0取整数作为一个参数,而不是硬编码为0。我工作在.NET 2.0所以lambda表达式是一个不走。它甚至有可能以一个参数传递到一个谓词?

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?

感谢您,

推荐答案

如果你坚持用C#2.0,使用匿名方法 - 只是一个稍微笨重lambda表达式(忽略表达式树):

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

如果你正在使用Visual Studio 2008,但的目标 .NET 2.0,但是,你仍然可以使用lambda表达式。这只是一个编译器的把戏,它不需要框架支持(再次,忽略表达式树)。

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

这篇关于在C#中添加参数为为的FindAll泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆