Click here to Skip to main content
Click here to Skip to main content

String concatenation using LINQ to create a CSV/PSV string

By , 26 Jun 2011
Rate this:
Please Sign up or sign in to vote.

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

License

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

About the Author


Comments and Discussions

 
GeneralI think this will be slower compared to the string.Join meth... PinmemberRakeshMeena26-Jun-11 19:18 
GeneralWhat is the performance difference between that and Join(sLi... Pinmemberdgauerke26-Jun-11 10:04 
GeneralWill it not be slow enough to go this way?! PinmemberRavi Sant26-Jun-11 8:37 
GeneralYou need to think about escaping as well as (pointed out alr... PinmemberHenry.Ayoola23-Jun-11 21:34 
GeneralThink there are syntax errors in the code. list.Aggregate sh... PinmemberGeorge Swan23-Jun-11 20:16 
GeneralRe: a type mistake. thanks for pointing out. PinmemberJP_Rocks26-Jun-11 8:35 
GeneralWould work OK for short lists. Would probably go with a Stri... PinprotectorAspDotNetDev23-Jun-11 5:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 26 Jun 2011
Article Copyright 2011 by JP_Rocks
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid