«
tweetz Update #5 |
Friday Links #66 »
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!
Comments
RE: Use LINQ Aggregate to Create Comma Separated Lists
by Brian Genisio
Tuesday, September 08, 2009 2:00 PM
In addition, I also like string.Join for this...
string.Join(", ", items);
RE: Use LINQ Aggregate to Create Comma Separated Lists
by Mike
Tuesday, September 08, 2009 2:14 PM
I meant to use ints in the example. My bad. Concept still applies...
powered by Bloget™