Ebooks

C# Predicate

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;

namespace SimpleEx
{
    class Program
    {
        static void Main(string[] args)
        {
          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;

namespace Anonymous
{
    class Program
    {
        static void Main(string[] args)
        {
          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;

namespace LambdaEx
{
    class Program
    {
        static void Main(string[] args)
        {
            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;

namespace NegateEx
{
    class Program
    {
        static void Main(string[] args)
        {
            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));
        }

        // static 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 ecapsulates a method that has one parameter and returns a value of the given type.

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

namespace PredicateEx
{
    class Person
    {
        public string Name { get; set; }
        public string Occupation { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var data = new List<Person>
            {
                new Person() { Name = "John Doe", Occupation = "gardener" },
                new Person() { Name = "Robert Brown", Occupation = "programmer" },
                new Person() { Name = "Lucia Smith", Occupation = "teacher" },
                new Person() { Name = "Thomas Neuwirth", Occupation = "teacher" }
            };

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

        }

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

            foreach (var person in data)
            {
                Console.WriteLine("{0}, {1}", person.Name, person.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.

Visit C# tutorial or list all C# tutorials.