Skip to content

Instantly share code, notes, and snippets.

@SuperYeti
Created May 6, 2011 21:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SuperYeti/959854 to your computer and use it in GitHub Desktop.
Save SuperYeti/959854 to your computer and use it in GitHub Desktop.
Convert C# object to CSV generic method.
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 linie = new StringBuilder();
foreach (var f in fields)
{
if (linie.Length > 0)
linie.Append(separator);
var x = f.GetValue(o);
if (x != null)
linie.Append(x.ToString());
}
return linie.ToString();
}
@asad-naeem
Copy link

If a class collection like List is passed in this function
List listCustomers = new List();
ToCsv(",", listCustomers);

Then replace the FieldInfo with PropertyInfo. This code is working for with this change.
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment