Skip to main content
4 of 4
edited tags; edited title
200_success
  • 144.2k
  • 22
  • 188
  • 473

Converting a list to a CSV string

I want to be able to convert a list of objects into a string csv format. I've written this extension method below but have a feeling I'm missing something as this seems like potentially a common thing to want to do.

private static readonly char[] csvChars = new[] { ',', '"', ' ', '\n', '\r' };

public static string ToCsv<T>(this IEnumerable<T> source, Func<T, object> getItem)
{
    if ((source == null) || (getItem == null))
    {
        return string.Empty;
    }

    var builder = new StringBuilder();
    var items = from item in source.Select(getItem) 
                where item != null 
                select item.ToString();
    
    foreach (var str in items)
    {
        if (str.IndexOfAny(csvChars) > 0)
        {
            builder.Append("\"").Append(str).Append("\"").Append(", ");
        }
        else
        {
            builder.Append(str).Append(", ");
        }
    }

    var csv = builder.ToString();

    return csv.Length > 0 ? csv.TrimEnd(", ".ToCharArray()) : csv;
}

Is there anything I can do to improve this or refactor to a more elegant or working solution. Or even an existing method out there already that I may have missed.

UPDATE: Updated to take into account quotations as per Jesse comments below.

dreza
  • 6.4k
  • 2
  • 29
  • 42