views:

117

answers:

1

I understand how to use delegates and I am okay with lambda expressions to make use of predicates. I've come to a point where I want to implement a method that uses a predicate as an argument and can't figure out how to reference the predicate to find the matches in my collection:

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

I want to then reference this using something akin to:

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

If anyone can give me an explanation or point me to a reference regarding implementation of predicates, I'd appreciate it. The documentation out there seems to all relate to passing predicates (which I can do just fine), not actually implementing the functionality that uses them...

Thanks

+7  A: 
private static T FindInCollection<T>(ICollection<T> collection, Predicate<T> match)
{
    foreach (T item in collection)
    {
        if (match(item))
            return item;
    }
    return default(T);
}

You just use the predicate like any other delegate. It's basically a method you can call with any argument of type T, which will return true.

Reed Copsey
Thank you, I just couldn't find any info on this one simple missing piece of the puzzle. Thanks for the swift response! +1
BobTheBuilder