views:

320

answers:

5

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.

A: 

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.

ChrisF
+3  A: 

Predicate is a type (more specifically, a delegate type) in the System namespace. It’s not a keyword.

Konrad Rudolph
If it is a type, then why isn't Predicate<T> used in the example? Are there any examples that use it? What is a delegate type vs just a type?
4thSpace
+1  A: 

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.

bobbymcr
A: 

The Predicate Type is there in 3.5 and in 4.0.

Mike Two
+5  A: 

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.

Ahmad Mageed