代码之家  ›  专栏  ›  技术社区  ›  Ocelot20

以谓词为参数的方法

  •  8
  • Ocelot20  · 技术社区  · 14 年前

    我有一个 Dictionary<int, List<string>>

    from x in Dictionary
    where x.Value.Contains("Test")
    select x.Key
    
    from x in Dictionary
    where x.Value.Contains("Test2")
    select x.Key
    

    所以我在寻找这样一种方法:

    public int GetResult(**WhatGoesHere** filter)
    {
        return from x in Dictionary.Where(filter)
               select x.Key;
    }
    

    int result;
    
    result = GetResult(x => x.Value.Contains("Test"));
    result = GetResult(x => x.Value.Contains("Test2"));
    

    正确的语法是什么 什么鬼东西 ?

    1 回复  |  直到 14 年前
        1
  •  15
  •   Community PPrice    7 年前

    你可以用 Func<KeyValuePair<int, List<string>>, bool>

    public int GetResult(Func<KeyValuePair<int, List<string>>, bool> filter)
    {
        return (from x in Dictionary
                where filter(x)
                select x.Key).FirstOrDefault();
    }
    

    或者: Predicate<KeyValuePair<int, List<string>>> Func 在.NET3.5中引入的是 preferred 这些天。

    x 在最后一个例子中表示两个不同的东西,这将给出一个编译错误。试着换一个 其他事情:

    x = GetResult(y => y.Value.Contains("Test1"));