Last Updated: February 25, 2016
·
375
· tyrodev

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();
}