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>ToCsv<T>(this IEnumerable<T> source, Func<T, object> getItem)
{
if ((source == null) || (getItem == null))
{
StringBuilderreturn string.Empty;
}
var builder = new StringBuilder();
var items = from item in source.Select(getItem)
where item != null
select item.ToString();
foreach (var objstr in sourceitems)
{
if (str.IndexOfAny(csvChars) > 0)
{
builder.Append(getItem(obj"\"").ToStringAppend(str).Append("\"").Append(", ");
string}
csv = builder.ToString();
else
if (csv.Length > 0)
{
return csv builder.TrimEndAppend(str).Append(", ".ToCharArray());
else}
}
var csv = builder.ToString();
return csv;
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.