Wednesday, 7 November 2007

The power of Lambda Functions

(Tip thanks to my mate Eric Phan):

Lambda functions are essentially anonymous functions (in-line functions) that you can write instead of creating a new method to perform this once off operation.

A good example is filtering a list

I have a list of customers and I want to know who is more than 25 years old and female.
Traditionally (using a filtering method):


   1:  static void Main(string[] args)

   2:  {

   3:     List<Customer> customers = GetAListOfCustomer();

   4:     List<Customer> matureFemaleCustomers = FindMatureFemaleCustomers(customers);

   5:  } 

   6:   

   7:  // Find female customers over 25 years old 

   8:  public List<Customer> FindMatureFemaleCustomers(List<Customer> customers)

   9:  {

  10:     List<Customer> matureFemaleCustomers =new List<Customer>();

  11:     foreach (Customer c in customers)

  12:     {

  13:        if (c.Age > 25 && c.Gender == Gender.Female)

  14:        {

  15:           matureFemaleCustomers.Add(c);

  16:        }

  17:     }

  18:     return matureFemaleCustomers;

  19:  } 


In C# 2.0 with generics:



   1:  static void Main(string[] args){ List<customer> customers = GetAListOfCustomer();

   2:  List<customer> matureFemaleCustomers = customers.FindAll( delegate(Customer c) { return c.Age > 25 && c.Gender == Gender.Female; } );}



In C# 3.0 with Lambda Functions



   1:  static void Main(string[] args) 

   2:  { List customers = GetAListOfCustomer(); 

   3:    List matureFemaleCustomers = customers.Where(c => c.Age > 25 && c.Gender == Gender.Female);

   4:  } 





Simple and elegant!

1 comment:

Unknown said...

Sir, this was the best lambda article for the persons who has just started learning C#. But code was not fully visible. Sir, please repost it. So that code is clearly visible.

Thank you in advance