Is Predicate available anywhere in .NET? From MSDN http://msdn.microsoft.com/en-us/library/bfcke1bz.aspx, I don't see a Predicate anywhere. I see an anonymous that returns a boolean but no generics or a "Predicate" keyword.
That page on MSDN is about the Predicate(T) Delegate, which as it states:
Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.
Predicate
is a type (more specifically, a delegate type) in the System
namespace. It’s not a keyword.
It is definitely in 3.0... see the bottom of that MSDN page:
Version Information
.NET Framework
Supported in: 3.5, 3.0, 2.0
As long as you are 'using System' you should see it.
Rather than inline a delegate for the predicate, you could use it as a type then pass it in. Here's an example:
var list = new List<int>();
list.AddRange(Enumerable.Range(1, 10));
Predicate<int> p = delegate(int i)
{
return i < 5;
};
list.RemoveAll(p);
list.ForEach(i => Console.WriteLine(i));
EDIT: to declare the Predicate with an existing method, you would use:
Predicate<int> p = IsLessThanFive;
public bool IsLessThanFive(int number)
{
return number < 5;
}
The alternatives, which are more common, would've been:
list.RemoveAll(delegate(int i) { return i < 5; });
// or...
list.RemoveAll(i => i < 5);
EDIT: to answer your other question in a comment to another post, a delegate is a type that defines a method signature and can be used to pass methods to other methods as arguments. If you're somewhat familiar with C++, they are like function pointers. For more info on delegates check out this MSDN page.