Know thy framework String to CSV String.Join

A common task is to take an array of strings or a List<string> and parse it to a comma separated value string for use in some sort of light weight media like a cookie or an url.

The way that this is usually done is to loop the array and concatenate the strings with a trailing comma “ , “ to then remove the last one.

Yesterday I was on my way in doing just this procedure when I thought that there’s got to be a better way to do this. After doing some research with our old friend Google I found a hidden gem in the String object in .NET. String.Join().
The name is somewhat misleading, at first glance it looks like it will just concatenate two strings, but no. This method takes an array of string and a separator string, it then uses the separator to create a CSV string with the separator as delimiter. The way I used it was like this

string categoryCsv = String.Join(",", IENumerable<T>.ToArray());

Some times you don’t need much to make your day, this definitely did, and it won’t be the last time I use it.
Here is a link to MSDN documentation http://msdn.microsoft.com/en-us/library/57a79xd0.aspx

Print | posted on Saturday, May 23, 2009 8:14 AM Filed Under .NET developement

Comments

Gravatar

# re: Know thy framework String to CSV String.Join, Posted by whiteness on 6/2/2009 5:52 AM

So I don't think, that it is a common task, maybe it is very easy for a professional, but I need to spend a lot of time to solve it.

Gravatar

# re: Know thy framework String to CSV String.Join, Posted by Kalle on 7/29/2009 7:18 AM

What part do you find hard to do? What takes time?

Gravatar

# re: Know thy framework String to CSV String.Join, Posted by north face jackets on sale on 10/27/2010 8:23 AM

Some times you don’t need much to make your day, this definitely did, and it won’t be the last time I use it.

Comments

Title: *
Name: *
Email: (never displayed)
Website:
Comment: *  
Please add 5 and 8 and type the answer here: