Let's say you need to aggregate one value from each object in a list into a single string. For Example, you want to send an e-mail to a set of customers. This requires a string with the email addresses seperated by a semicolon (;). The following code will create a generic List of Books, and provide a method ListAllEmails() that will print the delimited list of emails to the console window:
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Lambdas
{
/// <summary>
/// Define the Book Class
/// </summary>
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public double Price { get; set; }
public string EmailAddress { get; set; }
}
public List<Book> Books { get; private set; }
public Lambdas()
{
// Create a new list of Books
Books = new List<Book> {
new Book { Title = "Pro ASP.Net MVC Framework", Author = "Steven Sanderson", Price = 49.99, EmailAddress = "steve@nospam.com" },
new Book{ Title = "Pro Silverlight 2 in C# 2008", Author = "Matthew MacDonald", Price = 49.99, EmailAddress = "Matthew@nospam.com" },
new Book{ Title = "Pro VB 2008 and the .Net 3.5 Platform", Author = "Andrew Troelsen", Price = 59.99, EmailAddress = "Andrew@nospam.com" }
};
}
/// <summary>
/// Creates a semicolon (;) delimited list of email addresses
/// </summary>
public void ListAllEmails()
{
Console.WriteLine(this.Books.Select(b => b.EmailAddress).Aggregate((items, item) => items + "; " + item));
}
}
}
The Select Method selects the EmailAddress for each Book. The Aggregate method builds a list of the items based on the lambda expression. The result:
steve@nospam.com; Matthew@nospam.com; Andrew@nospam.com
Notice that this did not require any additional code to ensure there is no extra semi-colon at the beginning or end of the list, which is often required when using a loop to concatenate text.
Note: Be careful when using the Aggregate method because it is very inefficient on large numbers of strings. Consider using the String Join method instead.
In VB, the lambda would look like this:
Console.WriteLine(Books.Select(Function(b) b.EmailAddress).Aggregate(Function(items, item) items & "; " & item))
You can also filter the list of email addresses. For Example, suppose you want to send an email to all the authors who sell their books for under $50, telling them that you think you can sell their next book for $59.99:
/// <summary>
/// Creates a semicolon (;) delimited list of email addresses where the price of the book is under $50
/// </summary>
public void ListSomeEmails()
{
Console.WriteLine(this.Books.Where(b => b.Price < 50).Select(b => b.EmailAddress).Aggregate((items, item) => items + ", " + item));
}