Thursday, June 20, 2013

Predicates- small but beautiful

 
A predicate is a function that returns true or false & a predicate delegate is a reference to a predicate.
So basically a predicate delegate is a reference to a function that returns true or false. Predicates are very useful for filtering a list of values - here is an example.
 
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
     List list = new List { 1, 2, 3 };

     Predicate predicate = new Predicate(greaterThanTwo);

     List newList = list.FindAll(predicate);
    }

    static bool greaterThanTwo(int arg)
    {
     return arg > 2;
    }
}
Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
     List list = new List { 1, 2, 3 };

     List newList = list.FindAll(i => i > 2);
    }
}
 
OR use the plane old inline Function delegate:
 
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List list = new List { 1, 2, 3 };

        List newList = list.FindAll(delegate(int arg)
                           {
                               return arg> 2;
                           });
    }
}

Labels