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.
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));
If you want to get more information about lambda expressions, check the Tip #25 – Lambda Expressions