A predicate is a function that
returns Boolean true or false. A predicate delegate is a reference
to a predicate.A predicate delegate is a
delegate with the following signature:
- Return type
- bool
- Argument type
- generic
A predicate delegate thus is a delegate
which is capable of taking any custom type as an argument. Predicates are very
useful for filtering a list of values - here is an example.
using System.Collections.Generic;
public class Program
{
private static void Main(string[] args)
{
var list = new List<string>
{ "abc", "xyz", "pqr"};
var predicate = new Predicate<string>(EqualToAbc);
var newList =
list.FindAll(predicate);
}
private static bool EqualToAbc(string arg)
{
return arg.Equals("abc");
}
}
Now if you are using C # 3 Or Later
versions you can use a lambda to represent the predicate in a cleaner fashion:
using System;
using System.Collections.Generic;
public class Program
{
private static void Main(string[] args)
{
var list = new List<string>
{ "abc", "xyz", "pqr"};
var newList = list.FindAll(i =>
i.Equals(("abc");
}
}
No comments:
Post a Comment