我是使用谓词的新手,刚学会了如何编写:
Predicate<int> pre = delegate(int a){ a %2 == 0 };
Run Code Online (Sandbox Code Playgroud)
谓词将返回什么,以及编程时它如何有用?
我无法弄清楚如何根据我在运行时传入的值使用List上的"查找".如果您看到我的下面的代码,我希望能够在List中找到它的Path参数等于X的CustomClass,其中X将在运行时定义.
任何想法如何在列表上进行这样的查找?或者,如果不编写迭代器并手动执行查找,这是不可能的?在这种情况下,或许有一个关键的集合,我应该用它来代替?
private List<CustomClass> files;
public void someMethod()
{
Uri u= new Uri(www.test.com);
CustomClass cc = this.files.find( matchesUri(u) ); // WON'T LET ME DO THIS
}
private static bool matchesUri(List<CustomClass> cc, Uri _u)
{
return cc.Path == _u; }
public class CustomClass
{
private Uri path;
public Uri Path
{
get { return this.path; }
set { this.path = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
PS.我必须承认,我并没有完全遵循doco中的谓词内容,网址为http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx
我使用StringDictionary来存储键值对.我需要交替使用键和值,即我应该能够从值中获取键,因为在我的情况下,值将是不同的.
有没有直接的方法可以做到(没有循环)?或者,如果有任何其他收藏我可以用来实现这一目标?
目前我正在循环:
public String GetKeyFromValue(string value)
{
foreach (KeyValuePair<string, string> kvp in instance)
{
if (String.Equals(kvp.Value, value))
return kvp.Key;
}
throw new Exception ("Key not found in FilterControlMapping");
}
Run Code Online (Sandbox Code Playgroud)
任何帮助深表感谢.谢谢.
我读到'if'关键字是邪恶的,最好使用谓词替换if.然后我用Google搜索,但仍然没有得到它.
任何人都可以善待提供一个例子吗?