7

我的理解是,如果我想获取列表中某个项目的 ID,我可以这样做:

private static void a()
{
    List<string> list = new List<string> {"Box", "Gate", "Car"};
    Predicate<string> predicate = new Predicate<string>(getBoxId);
    int boxId = list.FindIndex(predicate);
}

private static bool getBoxId(string item)
{
    return (item == "box");
}

但是如果我想让比较动态呢?因此,我不想检查 item=="box",而是想将用户输入的字符串传递给委托,并检查 item==searchString。

4

4 回答 4

18

通过匿名方法或 lambda 使用编译器生成的闭包是在谓词表达式中使用自定义值的好方法。

private static void findMyString(string str)
{
    List<string> list = new List<string> {"Box", "Gate", "Car"};
    int boxId = list.FindIndex(s => s == str);
}

如果您使用的是 .NET 2.0(无 lambda),这也可以:

private static void findMyString(string str)
{
    List<string> list = new List<string> {"Box", "Gate", "Car"};
    int boxId = list.FindIndex(delegate (string s) { return s == str; });
}
于 2009-06-12T04:25:28.850 回答
2

你可以做

string item = "Car";
...

int itemId = list.FindIndex(a=>a == item);
于 2009-06-12T04:29:08.730 回答
1
string toLookFor = passedInString;
int boxId = list.FindIndex(new Predicate((s) => (s == toLookFor)));
于 2009-06-12T04:25:54.557 回答
0
List <string>  list= new List<string>("Box", "Gate", "Car");
string SearchStr ="Box";

    int BoxId= 0;
        foreach (string SearchString in list)
        {
            if (str == SearchString)
            {
                BoxId= list.IndexOf(str);
                break;
            }
        }
于 2015-06-15T13:27:07.433 回答