Func, Action and Predicate are generic inbuilt delegates present in System namespace. All three can be used with method, anonymous method and lambda expression.
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything. Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
A predicate, or more precisely a predicate functor, is a Boolean-valued function. It is often a unary function, checking one argument against a condition and returning the result. Disregarding functions depending on side effects, there are two nullary functions (without arguments). public static class Predicate.
Delegates defined within a generic class can use the generic class type parameters in the same way that class methods do. Generic delegates are especially useful in defining events based on the typical design pattern because the sender argument can be strongly typed and no longer has to be cast to and from Object.
A predicate is a function that returns true
or false
. A predicate delegate is a reference to a predicate.
So basically a predicate delegate is a reference to a function that returns true
or false
. Predicates are very useful for filtering a list of values - here is an example.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int> { 1, 2, 3 };
Predicate<int> predicate = new Predicate<int>(greaterThanTwo);
List<int> newList = list.FindAll(predicate);
}
static bool greaterThanTwo(int arg)
{
return arg > 2;
}
}
Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int> { 1, 2, 3 };
List<int> newList = list.FindAll(i => i > 2);
}
}
Leading on from Andrew's answer with regards to c#2 and c#3 ... you can also do them inline for a one off search function (see below).
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int> { 1, 2, 3 };
List<int> newList = list.FindAll(delegate(int arg)
{
return arg> 2;
});
}
}
Hope this helps.
Just a delegate that returns a boolean. It is used a lot in filtering lists but can be used wherever you'd like.
List<DateRangeClass> myList = new List<DateRangeClass<GetSomeDateRangeArrayToPopulate);
myList.FindAll(x => (x.StartTime <= minDateToReturn && x.EndTime >= maxDateToReturn):
There's a good article on predicates here, although it's from the .NET2 era, so there's no mention of lambda expressions in there.
What is Predicate Delegate?
1) Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework.
2) It is being used with lambda expression (=>). It takes generic type as an argument.
3) It allows a predicate function to be defined and passed as a parameter to another function.
4) It is a special case of a Func
, in that it takes only a single parameter and always returns a bool.
In C# namespace:
namespace System
{
public delegate bool Predicate<in T>(T obj);
}
It is defined in the System namespace.
Where should we use Predicate Delegate?
We should use Predicate Delegate in the following cases:
1) For searching items in a generic collection. e.g.
var employeeDetails = employees.Where(o=>o.employeeId == 1237).FirstOrDefault();
2) Basic example that shortens the code and returns true or false:
Predicate<int> isValueOne = x => x == 1;
now, Call above predicate:
Console.WriteLine(isValueOne.Invoke(1)); // -- returns true.
3) An anonymous method can also be assigned to a Predicate delegate type as below:
Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
bool result = isUpper("Hello Chap!!");
Any best practices about predicates?
Use Func, Lambda Expressions and Delegates instead of Predicates.
The predicate-based searching methods allow a method delegate or lambda expression to decide whether a given element is a “match.” A predicate is simply a delegate accepting an object and returning true or false: public delegate bool Predicate (T object);
static void Main()
{
string[] names = { "Lukasz", "Darek", "Milosz" };
string match1 = Array.Find(names, delegate(string name) { return name.Contains("L"); });
//or
string match2 = Array.Find(names, delegate(string name) { return name.Contains("L"); });
//or
string match3 = Array.Find(names, x => x.Contains("L"));
Console.WriteLine(match1 + " " + match2 + " " + match3); // Lukasz Lukasz Lukasz
}
static bool ContainsL(string name) { return name.Contains("L"); }
If you're in VB 9 (VS2008), a predicate can be a complex function:
Dim list As New List(Of Integer)(New Integer() {1, 2, 3})
Dim newList = list.FindAll(AddressOf GreaterThanTwo)
...
Function GreaterThanTwo(ByVal item As Integer) As Boolean
'do some work'
Return item > 2
End Function
Or you can write your predicate as a lambda, as long as it's only one expression:
Dim list As New List(Of Integer)(New Integer() {1, 2, 3})
Dim newList = list.FindAll(Function(item) item > 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With