Skip to content

Instantly share code, notes, and snippets.

@poychang
Last active December 3, 2018 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poychang/e4ca39b89e7b3002d64f9c213ade868a to your computer and use it in GitHub Desktop.
Save poychang/e4ca39b89e7b3002d64f9c213ade868a to your computer and use it in GitHub Desktop.
[Linq To CSV] #dotnet
public static class LinqToCSVHelper
{
public static string ToCsv<T>(this IEnumerable<T> items, bool hasHeader = true, bool hasWrapper = false, string separator = ",")
where T : class
{
var csvBuilder = new StringBuilder();
var properties = typeof(T).GetProperties();
var firstLine = hasHeader;
foreach (var item in items)
{
if (firstLine)
{
var header = string.Join(separator, properties.Select(p => p.Name.ToCsvValue(hasWrapper)).ToArray());
csvBuilder.AppendLine(header);
firstLine = false;
}
var line = string.Join(separator, properties.Select(p => p.GetValue(item).ToCsvValue(hasWrapper)).ToArray());
csvBuilder.AppendLine(line);
}
return csvBuilder.ToString();
}
private static string ToCsvValue<T>(this T item, bool hasWrapper)
{
var wrapper = hasWrapper ? "\"" : "";
if (item == null) return $"{wrapper}{wrapper}";
if (item is string && item.ToString().Contains("\""))
{
return string.Format($"\"{item.ToString().Replace("\"", "\"\"")}\"");
}
if (double.TryParse(item.ToString(), out var dummy))
{
return string.Format($"{item}");
}
return string.Format($"{wrapper}{item}{wrapper}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment