What is Predicate?


What is Predicate<T>?

Simply put it is a delegate which is looking for a method that accepts one parameter and returns true or false.

It is used by several methods in .Net Framework mostly in List<T> and Array.

for example ,If you have a list of Person class and try to find out who is less than 30 

public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }


var persons = new List<Person>()
                              {
                                  new Person(){Name="azadeh",Age=30},
                                  new Person(){Name="elham",Age=30},
                                  new Person(){Name="maryam",Age=31},
                                  new Person(){Name="asal",Age=28},
                                  new Person(){Name="arezoo",Age=27},
                                
                              };


You will see that all of them return a same result.


var inTwenties1 = persons.FindAll(x => x.Age < 30);
var inTwenties2 = persons.FindAll(Test);
var inTwenties3 = persons.FindAll(delegate(Person p) { return p.Age < 30; });

public static bool Test(Person p)
        {
            return p.Age < 30;
        }


Predicate <T> or Func<T, bool>?
These two are exactly same. The only difference is that Predicate is older than Func<T, bool>.






Comments