Convert IEnumerable to CSV with an extension method

Found this useful tidbit for converting IEnumerable<T> to a CSV…

From the article:
” I started writing it, but then decided to Google with Bing, and found a decent direction to start with at Mike Hadlow’s blog. He didn’t include all the code in the post, but it saved me some typing, so thanks Mike!

namespace FooFoo
{
public static class LinqToCSV
{
public static string ToCsv<T>(this IEnumerable<T> items)
where T : class
{
var csvBuilder = new StringBuilder();
var properties = typeof(T).GetProperties();
foreach (T item in items)
{
string line = string.Join(“,”,properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
csvBuilder.AppendLine(line);
}
return csvBuilder.ToString();
}

private static string ToCsvValue<T>(this T item)
{
if(item == null) return “\”\””;

if (item is string)
{
return string.Format(“\”{0}\””, item.ToString().Replace(“\””, “\\\””));
}
double dummy;
if (double.TryParse(item.ToString(), out dummy))
{
return string.Format(“{0}”, item);
}
return string.Format(“\”{0}\””, item);
}
}
}

Thanks Hansleman!
http://www.hanselman.com/blog/?date=2010-02-04

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *