[c#] Predicate Delegates in C#

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.

This question is related to c# .net predicate

The answer is


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);
    }
}

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

  • Declaration
  • Instantiation
  • INVACATION

learn more form http://asp-net-by-parijat.blogspot.in/2015/08/what-is-delegates-in-c-how-to-declare.html


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.


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!


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.


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"); }

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();
        }
    }
}

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.


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)

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to predicate

Using Predicate in Swift How to negate a method reference predicate How to wait until an element is present in Selenium? Find first element in a sequence that matches a predicate List<object>.RemoveAll - How to create an appropriate Predicate Predicate in Java What is a predicate in c#? Predicate Delegates in C#