c# list to csv code example

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

Example 2: turn list of string to csv c#

List<int> myValues;
string csv = String.Join(",", myValues.Select(x => x.ToString()).ToArray());

Example 3: how to write a list to csv c#

File.WriteAllLines("text.txt", lst.Select(x => string.Join(",", x)));