Is Predicate <T> not available in .NET 3.0+

Is Predicate available anywhere in .NET? From MSDN http://msdn.microsoft.com/en-us/library/bfcke1bz.aspx I don't see the predicate anywhere. I see an anonymous one that returns boolean but not generics or the Predicate keyword.

+2


source to share


5 answers


Instead of a built-in delegate for a predicate, you can use it as a type and then pass it. 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 a predicate using an existing method, you must use:

Predicate<int> p = IsLessThanFive;

public bool IsLessThanFive(int number)
{
    return number < 5;
}

      



Alternatives that are more common would be as follows:

list.RemoveAll(delegate(int i) { return i < 5; });
// or...
list.RemoveAll(i => i < 5);

      

EDIT: To answer your other question in a comment on 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 are familiar with C ++, they are like function pointers. For more information on delegates check this MSDN page .

+5


source


Predicate

is a type (more specifically, a delegate type) in a namespace System

. This is not a key word.



+3


source


It's definitely in 3.0 ... see the bottom of this MSDN page:

Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0

While you are using System, you should see it.

+1


source


This page on MSDN is about the Predicate (T) delegate, which it states:

Represents a method that defines a set of criteria and determines if the specified object meets those criteria.

0


source


The Type predicate is found in versions 3.5 and 4.0.

0


source







All Articles