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?

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 render the actual document type icons in the tree in Umbraco

This post gives you the code to be able to see the icons for your document types in the tree view ra…

Read Post

Code to help you debug an umbraco issue on a remote site

This post gives you some razor code to help you see the values of the IPublishedContent item's prope…

Read Post

How to fix corrupt accented characters in Excel for a C# export as CSV

This post will help you fix the issue where you csv export has corrupt characters when opening it in…

Read Post

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