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