65.9K
CodeProject is changing. Read more.
Home

String concatenation using LINQ to create a CSV/PSV string

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jun 23, 2011

CPOL
viewsIcon

44482

A tip to concatenate a set of strings using comma/pipe

Consider you have a set of string names: Chin, Rahul, and John. And you would like to build a comma separated string from the collection. We can do this using the Aggregate extension in LINQ as follows:

IEnumerable<string> sList = 
  new List<string> {"Chin", "Rahul", "John"};
var commaSeparated = sList.Aggregate((x, y) => x + "," + y);
var pipeSeparated = sList.Aggregate((x, y) => x + "|" + y);

Here is the expected output:

Chin,Rahul,John
Chin|Rahul|John