Thursday, May 10, 2012

Creating a list of comma separated values using String.Join()

I’ve seen a lot of extension methods that allowed you to create a list of comma separated values.
public static string ToCSV(this IEnumerable<string> input)
{
 var temp = String.Empty;
 
 foreach (var entry in input) {
  if (String.IsNullOrEmpty(temp)) {
   temp = entry;
 }
 else 
 {
  entry += ", " + entry;
 }
 return temp;
}

I even created a similar extension method myself until I discovered the String.Join method while reading this blog post by Scott Hanselman:
var temp = String.Join(", ", input)

1 comment:

Kristof Mattei said...

Joining strings with just comma can be bad, if the values of the cells contains comma. Can cause weird issues when reading the CSV :)