Can you explain to me:
- What is a Predicate Delegate?
- Where should we use predicates?
- Any best practices when using predicates?
Descriptive source code will be appreciated.
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):
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)
Predicate falls under the category of generic delegates in C#. This is called with one argument and always return the boolean type. Basically, the predicate is used to test the condition - true/false. Many classes support predicate as an argument. For example, list.findall expects the parameter predicate. Here is an example of predicate.
Imagine a function pointer with the signature:
<modifier> bool delegate myDelegate<in T>(T match);
Here is the example:
Node.cs:
namespace PredicateExample
{
class Node
{
public string Ip_Address { get; set; }
public string Node_Name { get; set; }
public uint Node_Area { get; set; }
}
}
Main class:
using System;
using System.Threading;
using System.Collections.Generic;
namespace PredicateExample
{
class Program
{
static void Main(string[] args)
{
Predicate<Node> backboneArea = Node => Node.Node_Area == 0 ;
List<Node> Nodes = new List<Node>();
Nodes.Add(new Node { Ip_Address = "1.1.1.1", Node_Area = 0, Node_Name = "Node1" });
Nodes.Add(new Node { Ip_Address = "2.2.2.2", Node_Area = 1, Node_Name = "Node2" });
Nodes.Add(new Node { Ip_Address = "3.3.3.3", Node_Area = 2, Node_Name = "Node3" });
Nodes.Add(new Node { Ip_Address = "4.4.4.4", Node_Area = 0, Node_Name = "Node4" });
Nodes.Add(new Node { Ip_Address = "5.5.5.5", Node_Area = 1, Node_Name = "Node5" });
Nodes.Add(new Node { Ip_Address = "6.6.6.6", Node_Area = 0, Node_Name = "Node6" });
Nodes.Add(new Node { Ip_Address = "7.7.7.7", Node_Area = 2, Node_Name = "Node7" });
foreach( var item in Nodes.FindAll(backboneArea))
{
Console.WriteLine("Node Name " + item.Node_Name + " Node IP Address " + item.Ip_Address);
}
Console.ReadLine();
}
}
}
Simply -> they provide True/False values based on condition mostly used for querying. mostly used with delegates
consider example of list
List<Program> blabla= new List<Program>();
blabla.Add(new Program("shubham", 1));
blabla.Add(new Program("google", 3));
blabla.Add(new Program("world",5));
blabla.Add(new Program("hello", 5));
blabla.Add(new Program("bye", 2));
contains names and ages. Now say we want to find names on condition So I Will use,
Predicate<Program> test = delegate (Program p) { return p.age > 3; };
List<Program> matches = blabla.FindAll(test);
Action<Program> print = Console.WriteLine;
matches.ForEach(print);
tried to Keep it Simple!
A delegate defines a reference type that can be used to encapsulate a method with a specific signature. C# delegate Life cycle: The life cycle of C# delegate is
learn more form http://asp-net-by-parijat.blogspot.in/2015/08/what-is-delegates-in-c-how-to-declare.html