Oce*_*t20 8 .net c# linq linq-to-objects predicate
这是一个普遍的问题,但这是我正在寻找解决方案的具体案例:
我有一个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
Run Code Online (Sandbox Code Playgroud)
所以我正在寻找一个像这样的方法:
public int GetResult(**WhatGoesHere** filter)
{
return from x in Dictionary.Where(filter)
select x.Key;
}
Run Code Online (Sandbox Code Playgroud)
要像这样使用:
int result;
result = GetResult(x => x.Value.Contains("Test"));
result = GetResult(x => x.Value.Contains("Test2"));
Run Code Online (Sandbox Code Playgroud)
WhatGoesHere的正确语法是什么?
Mar*_*ers 15
你可以使用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();
}
Run Code Online (Sandbox Code Playgroud)
或者:Predicate<KeyValuePair<int, List<string>>>.我认为Func最近在.NET 3.5中引入的是首选.
您x在最后一个示例中使用的意思是两个不同的东西,这将产生编译错误.尝试将其中一个更改x为其他内容:
x = GetResult(y => y.Value.Contains("Test1"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9121 次 |
| 最近记录: |