【问题标题】:Method with Predicate as Parameter以谓词为参数的方法
【发布时间】:2010-08-03 19:04:11
【问题描述】:

这是一个普遍的问题,但这是我正在寻找解决方案的具体案例:

我有一个Dictionary<int, List<string>> 我想应用各种谓词。我想要一种可以处理多个 LINQ 查询的方法,例如:

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"));

WhatGoesHere 的正确语法是什么?

【问题讨论】:

  • 糟糕,我错过了正确的类型。我删除了我的答案。 Mark Byer 的回答很好。

标签: c# .net linq linq-to-objects predicate


【解决方案1】:

你可以使用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&lt;KeyValuePair&lt;int, List&lt;string&gt;&gt;&gt;。我认为.NET 3.5 中引入的Func 现在是preferred

您在最后一个示例中使用x 来表示两个不同的东西,这将产生编译错误。尝试将xs 之一更改为其他内容:

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

【讨论】:

  • 啊,我以为我走对了。我在做 Predicate>> 但我想这没有多大意义。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多