How to create a CSV from a list of object ?
Do you need to export a collection of object into a CSV format?
Here is a way to quickly to that :
private string WriteCSV<T>(IEnumerable<T> items)
{
Type itemType = typeof(T);
var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance).OrderBy(p => p.Name);
// Build the header
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Join(";", props.Select(p => p.Name)));
foreach (var item in items)
{
var propsValue = props.Select(p => p.GetValue(item, null)).ToList();
for(int i = 0; i < propsValue.Count(); i++)
{
if (propsValue[i] != null)
{
sb.Append(value);
}
sb.Append(";");
}
sb.AppendLine();
}
return sb.ToString();
}
Written by Valentin Tyrode
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Csv
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#