List ForEach Method

Posted written by Paul Seal on October 04, 2015 C#

You may or may not be aware of the .ForEach() Method which is available on List<T> objects.

It is very handy for shortening your code.

Lets say you want to write a method which returns a list of MailAdress objects.  A more traditional way would be to do the following:

using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;

 public static List<MailAddress> GetListOfMailAddressesFromString(string emailAddresses)
    {
        List<MailAddress> addressList = new List<MailAddress>();
        foreach (var s in emailAddresses.Split(';').ToList())
        {
            addressList.Add(new MailAddress(s));
        }
        return addressList;
    }

A more concise way of doing it, would be to attach the .ForEach method to the list of email addresses.
Inside the ForEach, you use a lambda expression to get the value of each item in the list of strings and then use that in adding to the addressList.

using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;

public static List<MailAddress> GetListOfMailAddressesFromString(string emailAddresses)
    {
        List<MailAddress> addressList = new List<MailAddress>();
        emailAddresses.Split(';').ToList().ForEach(x => addressList.Add(new MailAddress(x)));
        return addressList;
    }