Gre*_*reg 7 c# collections predicate list find
我无法弄清楚如何根据我在运行时传入的值使用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
Pav*_*aev 12
使用lambda:
Uri u = new Uri("www.test.com");
CustomClass cc = this.files.Find(cc => cc.Path == u);
Run Code Online (Sandbox Code Playgroud)
或者如果你还想要一个命名方法:
static bool matchesUri(CustomClass cc, Uri _u)
{
return cc.Path == _u;
}
Uri u = new Uri("www.test.com");
CustomClass cc = this.files.Find(cc => matchesUri(cc, u));
Run Code Online (Sandbox Code Playgroud)