C# Predicate Delegates: Filtering and Checking Collections
Master C# Predicate delegates to efficiently filter and check elements in collections. This guide explains their functionality, syntax, and use cases, showing how to define custom conditions for streamlined data processing.
Predicate Delegates in C#
A `Predicate
`Predicate` Syntax
public delegate bool Predicate<in T>(T obj);
The `in` keyword before the type parameter `T` indicates that the delegate is contravariant (meaning you can pass in arguments of types derived from `T`). The delegate takes a single argument (`obj` of type `T`) and returns a boolean.
Common Uses of `Predicate`
- Filtering: Used with methods like `List
.FindAll()`, `Array.FindAll()`, etc., to select elements that match a given condition. - Validation: Check if data meets specific criteria before processing.
- Searching: Find elements in a collection that satisfy a particular condition.
Example 1: Filtering Even Numbers
using System;
using System.Collections.Generic;
using System.Linq;
public class PredicateExample {
public static void Main(string[] args) {
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
//Using a named method as a predicate
List<int> evenNumbers = numbers.FindAll(IsEven);
//Using a lambda expression as a predicate
List<int> oddNumbers = numbers.FindAll(n => n % 2 != 0);
// ... (code to print the results) ...
}
static bool IsEven(int number) { return number % 2 == 0; }
}
Example 2: Checking if a String is Uppercase
public class PredicateExample {
public static void Main(string[] args) {
Predicate<string> isUpper = IsUpper;
bool result = isUpper("HELLO"); // true
Console.WriteLine(result);
}
static bool IsUpper(string str) { return str.Equals(str.ToUpper()); }
}