Created
December 2, 2011 11:46
-
-
Save gideondsouza/1422966 to your computer and use it in GitHub Desktop.
An extension to export any IEnumerable<T> to CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
using System.Linq; | |
using System.Collections.Generic; | |
namespace Gideon.Extensions | |
{ | |
static class ExportToCsvExtension | |
{ | |
//awesomeness!! XD | |
//found this at http://mikehadlow.blogspot.com/2008/06/linq-to-csv.html tweaked and fixed it | |
private static string ToCsvValue<T>(this T item) where T : class | |
{ | |
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); | |
} | |
public static string AsCsv<T>(this IEnumerable<T> items) where T : class | |
{ | |
var csvBuilder = new StringBuilder(); | |
var properties = typeof(T).GetProperties(); | |
csvBuilder.AppendLine(String.Join(",", properties.Select(p => p.Name.ToCsvValue()).ToArray())); | |
foreach (T item in items) | |
{ | |
string line = String.Join(",", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray()); | |
csvBuilder.AppendLine(line); | |
} | |
return csvBuilder.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment