Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

object list to csv c#

private void SaveToCsv<T>(List<T> reportData, string path)
{
    var lines = new List<string>();
    IEnumerable<PropertyDescriptor> props = TypeDescriptor.GetProperties(typeof(T)).OfType<PropertyDescriptor>();
    var header = string.Join(",", props.ToList().Select(x => x.Name));
    lines.Add(header);
    var valueLines = reportData.Select(row => string.Join(",", header.Split(',').Select(a => row.GetType().GetProperty(a).GetValue(row, null))));
    lines.AddRange(valueLines);
    File.WriteAllLines(path, lines.ToArray());
}
 
PREVIOUS NEXT
Tagged: #object #list #csv
ADD COMMENT
Topic
Name
8+8 =