How to do Lambda Expressions: The ForEach clause

How many times have you written code such as:

Customer[] customers = Customer.GetAllActiveCustomers();
foreach (Customer c in customers)
  Debug.WriteLine("Name:" + c.Name);
  Debug.WriteLine("Age:" + c.Name);

 Well, using lambda expressions, you can now take a shortcut!

The above code can now be written like this:

var customers = Customer.GetAllActiveCustomers();
customers.ForEach(c =>
  Debug.WriteLine("Name:" + c.Name);
  Debug.WriteLine("Age:" + c.Name);

I don’t know about you, but this seems to be easier to read. It follows object-oriented principles of executing methods directly off objects. No need to add overly obvious repetitive code. The compiler works out the types for you!

The => token is a direct substitute for the delegate clause. When the compiler sees the =>, it says that the preceeding part of the statement is the parameter list of a delegate, and what follows the =>  is the statement to execute.  

Most collection types now contain a number of methods that allow lambda expressions, and therefore delegates also, to be supplied. ForEach is one of these. I hope to see more statements like this in the code I see when I’m out consulting!

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: