C# List.Find 方法 - 如何将值传递给谓词?

标签 c# list collections find predicate

我无法弄清楚如何根据我将在运行时传入的值对我拥有的列表进行“查找”。如果您看到我下面的代码,我希望能够在其路径参数等于 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; }
    }
}

附言。我必须承认我不太了解 http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx 的 doco 中的谓词内容。

最佳答案

使用 lambda:

 Uri u = new Uri("www.test.com");
 CustomClass cc = this.files.Find(cc => cc.Path == u);

或者如果您仍然想要一个命名方法:

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

关于C# List.Find 方法 - 如何将值传递给谓词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1529846/

相关文章:

c# - Process.ProcessorAffinity 和 Thread.ProcessorAffinity 之间的区别

c# - Linq to SQL 检查数据是否存在并更新/插入,具体取决于

c# - 是否使用另一个列表复制值或引用初始化了通用列表?

list - 如何在列表中连接用户输入

php - 如何 array_values laravel 集合?

java - 如何从java 8中的对象列表中获取最大数量的所有不同元素

javascript - 从 appdata 文件夹在 Windows 应用商店应用程序中加载 html

python - 如何将列表中元组的第 i 个元素映射到另一个列表中的键以形成字典

java - hamcrest containsInAnyOrder 仅适用于特定订单

c# - HtmlTable 和 TagBuilder 的区别 ("table")