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;
    }

Want to thank me?

If I've helped you out and you want to thank me, why not buy me a coffee?

About the author

Paul Seal

Umbraco MVP and .NET Web Developer from Derby (UK) who specialises in building Content Management System (CMS) websites using MVC with Umbraco as a framework. Paul is passionate about web development and programming as a whole. Apart from when he's with his wife and son, if he's not writing code, he's thinking about it or listening to a podcast about it.

Related Posts

How to include scripts from partial views in MVC and Umbraco

This post will show you how you can include scripts from inside an MVC partial view rather than havi…

Read Post

How to solve the error "Could not load file or assembly 'Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0 ..."

This post will show you how to solve the error "Could not load file or assembly 'Microsoft.CodeDom.P…

Read Post

How to upload multiple files at once in an MVC form

This post will help you if you need to upload multiple files at once in an MVC form.  The examples…

Read Post

How to force a .NET website to use TLS 1.2

This post shows you how you can force your .NET website to run using TLS 1.2

Read Post