Skip to content

Instantly share code, notes, and snippets.

@pkskelly
Created April 14, 2015 19:40
Show Gist options
  • Save pkskelly/ad7d26c1319f77b57d93 to your computer and use it in GitHub Desktop.
Save pkskelly/ad7d26c1319f77b57d93 to your computer and use it in GitHub Desktop.
Simple (Very) C# Extension Method for conversion to a CSV list
public static string ToCsv<T>(string separator, IEnumerable<T> objectlist)
{
Type t = typeof(T);
FieldInfo[] fields = t.GetFields();
string header = String.Join(separator, fields.Select(f => f.Name).ToArray());
StringBuilder csvdata = new StringBuilder();
csvdata.AppendLine(header);
foreach (var o in objectlist)
{
csvdata.AppendLine(ToCsvFields(separator, fields, o));
}
return csvdata.ToString();
}
public static string ToCsvFields(string separator, FieldInfo[] fields, object o)
{
StringBuilder line = new StringBuilder();
foreach (var f in fields)
{
if (line.Length > 0)
line.Append(separator);
var x = f.GetValue(o);
if (x != null)
line.Append(x.ToString());
}
return line.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment