Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

String concatenation using LINQ to create a CSV/PSV string

5.00/5 (1 vote)
26 Jun 2011CPOL 44.4K  
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:


C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)