Skip to content

Instantly share code, notes, and snippets.

@tonyjoanes
Created November 25, 2015 14:31
Show Gist options
  • Save tonyjoanes/71220cff3a16864eec72 to your computer and use it in GitHub Desktop.
Save tonyjoanes/71220cff3a16864eec72 to your computer and use it in GitHub Desktop.
Convert a generic list to CSV
private static string CreateCsvTextFile<T>(List<T> data)
{
var properties = typeof(T).GetProperties();
var result = new StringBuilder();
var headings = properties.Select(x => x.Name.ToString());
var headerLine = string.Join(",", headings);
result.AppendLine(headerLine);
foreach (var row in data)
{
var values = properties.Select(p => p.GetValue(row, null))
.Select(v => StringToCsvCell(Convert.ToString(v)));
var line = string.Join(",", values);
result.AppendLine(line);
}
return result.ToString();
}
private static string StringToCsvCell(string str)
{
bool mustQuote = (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"));
if (mustQuote)
{
StringBuilder sb = new StringBuilder();
sb.Append("\"");
foreach (char nextChar in str)
{
sb.Append(nextChar);
if (nextChar == '"')
sb.Append("\"");
}
sb.Append("\"");
return sb.ToString();
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment