Translate

Sunday, December 18, 2011

Predicate C#

What is a Predicate?

The predicate is just a generic delegate that is defined in the .net framework class library. In the framework library, it is defined as


public delegate bool Predicate<T>(T obj);

This delegate is used for searching purposes.


Predicate Example

The FindAll() method in List<T> expects an instance of the predicate as a parameter. In the example below I show you how to do that.

  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace PlayLambda
{
    public class Person
    {
        public string name;
        public int Age;

    }

    class Program
    {

        static void Main(string[] args)
        {
            Person P1 = new Person();
            P1.name = "Mike";
            P1.Age = 37;

            Person P2 = new Person();
            P2.name = "Tommy";
            P2.Age = 13;

            Person P3 = new Person();
            P3.name = "Kim";
            P3.Age = 27;



            List<Person> People = new List<Person>();

            People.Add(P1);
            People.Add(P2);
            People.Add(P3);

            Predicate<Person> myPredicate = IsDrinkingAge;

                     //FindAll() expects an instance of the Predicate as a parameter
            foreach (Person p in People.FindAll(myPredicate))
            {
                Console.WriteLine("This person can legally drink: " + p.name);
            }


        }

        static bool IsDrinkingAge(Person p)
        {
            //The signature of this method should match the signature of the predicate
            if (p.Age > 21)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
    }

}
  

Shown below is the output of this program



No comments:

Post a Comment

Comments will appear once they have been approved by the moderator