C# predicate
时间: 2025-01-23 11:03:24 浏览: 38
### C# Predicate Usage and Examples
In C#, `Predicate<T>` represents a method that takes an object of type T as its parameter and returns a boolean value indicating whether the specified object meets certain criteria[^1]. Predicates are commonly used in methods like `Find`, `FindAll`, among others to filter elements from collections.
#### Basic Syntax
A predicate delegate is defined using the following signature:
```csharp
public delegate bool Predicate<in T>(T obj);
```
Here, `T` specifies the type of the argument passed into the method represented by this delegate. The method must take one parameter of type `T` and return a Boolean value.
#### Example Code Demonstrating Predicate Use
To illustrate how predicates work within lists, consider the example below where a list of integers gets filtered based on custom conditions provided via predicates:
```csharp
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<int> numbers = new List<int>{ 1, 2, 3, 4, 5 };
// Define a simple predicate function.
Predicate<int> greaterThanThree = delegate(int i) {
return i > 3;
};
int firstMatchedNumber = numbers.Find(greaterThanThree);
Console.WriteLine($"First number greater than three: {firstMatchedNumber}");
// Using lambda expression instead of anonymous method
var evenNumbers = numbers.FindAll(x => x % 2 == 0);
foreach(var num in evenNumbers){
Console.WriteLine(num);
}
}
}
```
This code snippet demonstrates defining both traditional delegates and lambda expressions for filtering purposes. It also shows practical application scenarios such as finding all matching items (`FindAll`) versus just locating the first occurrence (`Find`).
阅读全文
相关推荐


















