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

Bob*_*der 1 c# generics predicate

我理解如何使用委托,我可以使用lambda表达式来使用谓词.我已经到了一个点,我想实现一个使用谓词作为参数的方法,并且无法弄清楚如何引用谓词来查找我的集合中的匹配:

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);
}
Run Code Online (Sandbox Code Playgroud)

我想用类似的东西来引用它:

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

如果有人可以给我一个解释或指出我关于谓词实现的参考,我会很感激.那里的文档似乎都与传递谓词(我可以做得很好)有关,而不是实际实现使用它们的功能......

谢谢

Ree*_*sey 7

private static T FindInCollection<T>(ICollection<T> collection, Predicate<T> match)
{
    foreach (T item in collection)
    {
        if (match(item))
            return item;
    }
    return default(T);
}
Run Code Online (Sandbox Code Playgroud)

您只需像任何其他委托一样使用谓词.它基本上是一个可以使用类型T的任何参数调用的方法,它将返回true.