Posted by: Cirilo Meggiolaro | 12/21/2008

Tip of the day #68 – Using generic ForEach method in collections

One of the good things that have been implemented by Microsoft is the ability to code faster. New features and libraries really make shorter the coding phase and when you have strict deadlines to finish coding an application it counts a lot.

Let’s check today a way to make a simple foreach loop using the ForEach function available under the System.Collections.Generic.List<T> object.

How to…

As any other function available under the generic List<T> object you may use lambda expressions, define delegates to perform the tasks and so on. For this example we are going to use a simple lambda expression. The code is self explanatory:

/// Creates a generic list of strings that stores
/// application error messages
List<string> errorMessages = new List<string>();

/// Adds some messages
errorMessages.Add(“Client has bad credit history.”);
errorMessages.Add(“Client credit card is invalid.”);
errorMessages.Add(“There is no products in stock.”);

Console.WriteLine(“The order cannot be completed because:”);

/// Using the ForEach method, defines a lambda expression
/// that takes the current string and writes it to the console.

errorMessages.ForEach(myText => Console.WriteLine(myText));

Output:

Picture 1 - The code outputs the messages included in the generic collection.

Picture 1 - The code outputs the messages included in the generic collection.

If you want to get more information about lambda expressions, check the Tip #25 – Lambda Expressions


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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

Categories

%d bloggers like this: