ZetCode

C# Predicate

last modified April 4, 2021

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

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.

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

The IsPositive returs true for all values greater than zero.

$ dotnet run
1,3,2

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

C# Predicate Exists

The Exists method of a list determines whether the list contains elements that match the conditions defined by the specified predicate.

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

var words = new List<string> { "sky", "", "club", "spy", "silk", "summer",
        "war", "cup", "cloud", "coin", "small", "terse", "",
        "snow", "snail", "see"};

Predicate<string> pred = String.IsNullOrEmpty;

if (words.Exists(pred))
{
    Console.WriteLine("There is an empty string");
}
else
{
    Console.WriteLine("There is no empty string");
}

We check if there are some empty strings in the list.

$ dotnet run 
There is an empty string

C# Predicate RemoveAll

The RemoveAll method of a list removes all the elements that match the conditions defined by the specified predicate.

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

var words = new List<string> { "sky", "town", "club", "spy", "silk", "snail",
        "war", "cup", "cloud", "coin", "small", "terse"};

Predicate<string> HasThreeChars = word => word.Length == 3;

words.RemoveAll(HasThreeChars);

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

We have a list of words. We remove all words which have three latin characters.

$ dotnet run 
town, club, silk, snail, cloud, coin, small, terse

C# Predicate multiple conditions

The next example uses a predicate with two conditions.

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

var countries = new List<Country>
{
    new Country("Iran", 80840713),
    new Country("Hungary", 9845000),
    new Country("Poland", 38485000),
    new Country("India", 1342512000),
    new Country("Latvia", 1978000),
    new Country("Vietnam", 95261000),
    new Country("Sweden", 9967000),
    new Country("Iceland", 337600),
    new Country("Israel", 8622000)
};

Predicate<Country> p1 = c => c.Name.StartsWith("I");
Predicate<Country> p2 = c => c.Population > 1000_0000;

Predicate<Country> CombineAnd = c => (p1(c) && p2(c));

var result = countries.FindAll(CombineAnd);
Console.WriteLine(string.Join(", ", result));

record Country(string Name, int Population);

We create a list of countries. We find all countries that start with 'I' and have population over one million.

Predicate<Country> p1 = c => c.Name.StartsWith("I");
Predicate<Country> p2 = c => c.Population > 1000_0000;

We define two predicates.

Predicate<Country> CombineAnd = c => (p1(c) && p2(c));

We combine the two predicates.

var result = countries.FindAll(CombineAnd);

We apply the combined predicate to the FindAll method.

$ dotnet run
Country { Name = Iran, Population = 80840713 }, Country { Name = India, ...

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.