Lambdas: Aggregating Strings
Posted
Fri, Jul 3 2009 10:24
by
Deborah Kurata
Looping through a list to append strings is often more challenging than it should be. For example…
In C#:
string emailAddresses=string.Empty;
foreach (Customer c in custList)
{
emailAddresses += c.EmailAddress + ";";
}
In VB:
Dim emailAddresses As String = String.Empty
For Each c As Customer In custList
emailAddresses &= c.EmailAddress & ";"
Next
Both of these examples pose a problem because the emailAddresses string ends up with an extra “;” at the end. So you can add extra code to remove it after the loop, add code in the loop that checks whether you are on the last one and skip appending the “;”, or append the “;” to the beginning instead and skip the first one. In any case, it wastes time to deal with this.
NOTE: The definition of the Customer class and the list of customers (custList) used in this example can be found here.
Using lambda expressions and the Aggregate extension method, this task is a breeze:
[To begin with an overview of lambda expressions, start here.]
In C#:
string email = custList.Select(c => c.EmailAddress)
.Aggregate((items, item) => items + "; " + item);
In VB:
Dim email As String = custList.Select(Function(c) c.EmailAddress) _
.Aggregate(Function(items, item) items & "; " & item)
The Select method first selects the email address for each customer. The Aggregate method then appends the email addresses together. And this code correctly handles the '”;” so you don’t have to think about it.
Enjoy!