代码之家  ›  专栏  ›  技术社区  ›  BobTheBuilder

如何使用谓词实现匹配算法?

  •  1
  • BobTheBuilder  · 技术社区  · 17 年前

    private static T FindInCollection<T>(ICollection<T> collection, Predicate<T> match)
    {
        foreach (T item in collection)
        {
            //So how do I reference match to return the matching item?
        }
        return default(T);
    }
    

    ICollection<MyTestClass> receivedList = //Some list I've received from somewhere else
    MyTestClass UsefulItem = FindInCollection<MyTestClass>(receivedList, i => i.SomeField = "TheMatchingData");
    

    1 回复  |  直到 17 年前
        1
  •  7
  •   Reed Copsey    17 年前
    private static T FindInCollection<T>(ICollection<T> collection, Predicate<T> match)
    {
        foreach (T item in collection)
        {
            if (match(item))
                return item;
        }
        return default(T);
    }
    

    推荐文章