Tuesday 20 October 2009

Creating comma separated strings with LINQ

Here is a really quick LINQ based solution to the conversion of a collection of strings into a comma separated string:

//Prepare list
List myList = new List();
myList.Add("aString");
myList.Add("anotherstring");

//Get comma separated string

var stringBuilder = myList.Aggregate(new StringBuilder(), (builder, stringValue) =>
builder.AppendFormat((builder.Length == 0) ? "{0}" : ", {0}", stringValue));
string commaString = stringBuilder.ToString();

No comments: