I don't think my question is a duplicate because I am not asking how to convert Lists in to CSVs. But:
I am trying to convert a list into a comma-delimited csv file.
However, some fields contain commas and semicolons.
A column will be split into at least two columns when there is a comma.
My codes:
public void SaveToCsv<T>(List<T> listToBeConverted)
{
var lines = new List<string>();
IEnumerable<PropertyDescriptor> props = TypeDescriptor.GetProperties(typeof(T)).OfType<PropertyDescriptor>();
//Get headers
var header = string.Join(",", props.ToList().Select(x => x.Name));
//Add all headers
lines.Add(header);
//LinQ to get all row data and add commas to serperate them
var valueLines = listToBeConverted.Select(row => string.Join(",", header.Split(',').Select(a => row.GetType().GetProperty(a).GetValue(row, null))));
//add row data to List
lines.AddRange(valueLines);
...
}
How do I modify the LinQ statment to add double quotes to the start and the end of the string when it is System.String
?