Let's say we want to filter even numbers. In C#, we usually do it using LINQ's Where
extension -
var numbers = Enumerable.Range(1, 100);
var evenNumbers = numbers.Where(n => n % 2 == 0);
The signature of Where
takes Func<int, bool>
as parameter
The syntactic sugar, behind the scenes, is basically doing
var evenNumbers = numbers.Where(new Func<int, bool>(n => n % 2 == 0));
Func is a delegate which has int
as input and bool
as output. We can write it as -
var evenNumbers = numbers.Where(delegate(int n)
{
return n % 2 == 0;
});
This means we can do -
public static bool IsEven(int number)
{
return number % 2 == 0;
}
var evenNumbers = numbers.Where(IsEven);
Top comments (0)