Last active
December 3, 2018 00:49
-
-
Save poychang/e4ca39b89e7b3002d64f9c213ade868a to your computer and use it in GitHub Desktop.
[Linq To CSV] #dotnet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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