Use LINQ Aggregate to Create Comma Separated Lists

It’s a common problem. You’re handed a collection of strings or numbers and you need emit a comma separated list. The usual approach I’ve seen (and done) is to resort to a loop and some check to if it’s the first or last element to control when the comma is added.

var items = new string[] { "Wine", "Cheese", "Bread" };  
bool first = true;  
string picnicItems = string.Empty;  
foreach (var item in items)  
    if (!first)  
        picnicItems += ", ";  
    first = false;  
    picnicItems += item;  

I’ve always felt dissatisfied with doing this but could never find the energy to do something about it.

Enter the LINQ Aggregate extension method. As the name implies, it will “Aggregate” an IEnumerable using a given function.

var items = string[] { "Wine", "Cheese", "Bread" };  
var picnicItems = items.Aggregate((s1,s2) => s1 + ", " + s2);  

Much nicer IMHO. Also, if there is only one item in the list, it correctly creates the string without the comma. Sweet!

← newer older →
.Net, Technology, Life, Whatever

Recent Posts

Quick Tip - Clear ReSharper's Cache to Fix False Errors
Quick Tip - Refined GitHub
Vertical Layout for HTML Tables
Visual Studio 2017 Installer Quick Tip
VSColorOutput for VS 2017 Released
Quick ReSharper tip for inline templates
NoSQL vs. NewSQL: What's the Difference?
More... (1077)

Donate with PayPal