The Predicate
delegate in C# is a powerful tool for handling methods that evaluate conditions and return a bool result. It’s ideal for scenarios where you need to filter or search through collections based on specific criteria. This guide provides a thorough explanation of the Predicate
delegate, its syntax, and usage, with examples and real-world applications.
The Predicate
delegate in C# is used to define methods that take a single parameter and return a boolean result (true
or false
). This delegate is especially useful for filtering or searching within collections. It resides in the System namespace and is widely used with collection types, such as List<T>
, to identify elements that meet specific criteria.
Predicate
delegate takes exactly one input parameter.Find
, FindAll
, Exists
, etc.The Predicate
delegate is defined as follows:
Predicate<T>
T
: The type of the parameter for the method it encapsulates.Predicate<int> isEven = number => number % 2 == 0;
Console.WriteLine(isEven(4)); // Output: True
Console.WriteLine(isEven(3)); // Output: False
In this example:
Predicate<int>
defines a delegate with one int
parameter (number) and returns a boolean.This example defines a Predicate<int>
that checks if a number is odd.
Predicate<int> isOdd = number => number % 2 != 0;
Console.WriteLine(isOdd(5)); // Output: True
Console.WriteLine(isOdd(8)); // Output: False
Predicate<int>
specifies a delegate with one integer parameter.number => number % 2 != 0
evaluates to true if the number is odd.Find
MethodIn this example, we use a Predicate<string>
to search for a specific word in a list of strings.
List<string> names = new List<string> { "Alice", "Bob", "Charlie", "David" };
Predicate<string> isNameBob = name => name == "Bob";
string foundName = names.Find(isNameBob);
Console.WriteLine(foundName); // Output: Bob
Predicate<string>
checks if a name is "Bob
".Find
method in the list uses this predicate to search for the first occurrence that matches the condition.FindAll
MethodFindAll
returns all items that meet the condition specified by the predicate.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Predicate<int> isGreaterThanFive = number => number > 5;
List<int> results = numbers.FindAll(isGreaterThanFive);
results.ForEach(Console.WriteLine); // Output: 6 7 8 9
Predicate<int>
defines a condition to find numbers greater than five.FindAll
retrieves all matching elements.In this example, we use a Predicate to filter a list of customers based on a specific criterion—checking if they are "premium" members.
using System;
using System.Collections.Generic;
class Customer
{
public string Name { get; set; }
public bool IsPremium { get; set; }
}
class Program
{
static void Main()
{
List<Customer> customers = new List<Customer>
{
new Customer { Name = "Alice", IsPremium = true },
new Customer { Name = "Bob", IsPremium = false },
new Customer { Name = "Charlie", IsPremium = true },
new Customer { Name = "David", IsPremium = false }
};
Predicate<Customer> isPremiumCustomer = customer => customer.IsPremium;
List<Customer> premiumCustomers = customers.FindAll(isPremiumCustomer);
Console.WriteLine("Premium Customers:");
premiumCustomers.ForEach(c => Console.WriteLine(c.Name));
// Output:
// Premium Customers:
// Alice
// Charlie
}
}
isPremiumCustomer
: The Predicate<Customer>
checks if a customer is a premium member.FindAll
: This method uses the predicate to retrieve all premium customers from the list.Predicate
delegate always returns a bool, making it ideal for conditional checks.The Predicate
delegate in C# is designed for methods that require a single input parameter and return a bool, making it perfect for evaluating conditions. Its primary use is for filtering and searching collections based on specified criteria, like identifying items that match certain characteristics. With the flexibility of lambda expressions, predicates allow for concise and expressive code, enabling effective and modular conditional logic, especially when working with collections like List<T>
.