ZetCode

C# Predicate

last modified October 29, 2020

C# Predicate tutorial shows how to use predicates in C#. With predicates, we can create code that is more clean and readable.

Predicate

Predicate in general meaning is a statement about something that is either true or false. In programming, predicates represent single argument functions that return a boolean value.

C# Predicate

Predicates in C# are implemented with delegates. The Predicate delegate represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

C# Predicate example

The following example creates a simple C# Predicate.

Program.cs
using System;
using System.Collections.Generic;

var data = new List<int> { 1, -2, 3, 0, 2, -1 };

var predicate = new Predicate<int>(isPositive);
var filtered = data.FindAll(predicate);

Console.WriteLine(string.Join(",", filtered));

static bool isPositive(int val)
{
    return val > 0;
}

In the example, the predicate is used to filter out positive values.

var predicate = new Predicate<int>(IsPositive);

A predicate delegate is defined; it takes the IsPositive method as parameter.

var filtered = data.FindAll(predicate);

We pass the predicate to the FindAll method of a list, which retrieves all values for which the predicate returns true.

static bool IsPositive(int val)
{
   return val > 0;
}

The IsPositive returs true for all values greater than zero.

$ dotnet run
1,3,2

This is the output.

C# Predicate with anonymous method

The following example passes an anonymous method to the delegate.

Program.cs
using System;
using System.Collections.Generic;

var data = new List<int> { 1, -2, 3, 0, 2, -1 };

Predicate<int> isPositive = delegate(int val) { return val > 0; };
var filtered = data.FindAll(isPositive);

Console.WriteLine(string.Join(",", filtered));

The example uses the delegate keyword to define an anonymous method.

C# Predicate with lambda expression

C# lambda expression simplifies the creation of C# Predicates. Lambda expressions are created with the => lambda declaration operator.

Program.cs
using System;
using System.Collections.Generic;

var words = new List<string> { "falcon", "wood", "tree",
    "rock", "cloud", "rain" };

Predicate<string> hasFourChars = word => word.Length == 4;

var words2 = words.FindAll(hasFourChars);
Console.WriteLine(string.Join(',', words2));

In the example, we find out all words that have four letters.

$ dotnet run
wood,tree,rock,rain

This is the output.

C# negating predicates

We can create a delegate that negates an already defined delegate.

Program.cs
using System;
using System.Collections.Generic;

var words = new List<string> { "falcon", "wood", "tree",
    "rock", "cloud", "rain" };

Predicate<string> HasFourChars = word => word.Length == 4;
Predicate<string> Negate = word => !HasFourChars(word);

var words2 = words.FindAll(Negate);

Console.WriteLine(string.Join(',', words2));


// Predicate<T> Negate<T>(Predicate<T> predicate)
// {
//    return x => !predicate(x);
// }

The example negates the HasFourChars delegate. An alternative solution is commented out.

$ dotnet run
falcon,cloud

These are the words whose length is not four letters.

C# predicate with Func

The Func is a generic delegate type. It can contain 0 to 16 input parameters and must have one return type.

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;

var data = new List<Person>
{
    new Person("John Doe", "gardener"),
    new Person("Robert Brown", "programmer"),
    new Person("Lucia Smith", "teacher"),
    new Person("Thomas Neuwirth", "teacher")
};

ShowOutput(data, r => r.Occupation == "teacher");

void ShowOutput(List<Person> list, Func<Person, bool> condition)
{
    var data = list.Where(condition);

    foreach (var person in data)
    {
        Console.WriteLine($"{person.Name}, {person.Occupation}");
    }
}

record Person(string Name, string Occupation);

The example creates a list of persons. The ShowOutput method takes a predicate as the second parameter. It returns all persons who are teachers.

In this tutorial, we have worked with C# Predicate.

Visit C# tutorial or list all C# tutorials.