Saturday, June 1, 2013

C# Predicate, Anonymous Delegate & Lambda Expression usage to get same result

Predicate:

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;
    }
}
 

Anonymous 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;
                           });
    }
}

Lambda Expression:

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);
    }
} 
 
Reference 

No comments: