Created
July 4, 2015 20:24
-
-
Save gazlu/f7b1eef723b8dbeea270 to your computer and use it in GitHub Desktop.
Simple.Data ResultSet to CSV
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 CSVHelper | |
{ | |
/// <summary> | |
/// Usage: | |
/// CSVHelper.ToCsv( | |
/// ",", | |
/// resultSet, | |
/// new List<KeyValuePair<string, string>> | |
/// { | |
/// new KeyValuePair<string,string>("caf_no", "'") | |
/// }.ToArray() | |
/// ) | |
/// </summary> | |
/// <param name="separator"></param> | |
/// <param name="resultSet"></param> | |
/// <param name="encapsulations"></param> | |
/// <returns></returns> | |
public static string ToCsv(string separator, SimpleResultSet resultSet, params KeyValuePair<string, string>[] encapsulations) | |
{ | |
string header = String.Join(separator, resultSet.GetDynamicMemberNames().Select(f => f).ToArray()); | |
IEnumerable<SimpleRecord> objectlist = resultSet.ToList<SimpleRecord>(); | |
StringBuilder csvdata = new StringBuilder(); | |
if (string.IsNullOrWhiteSpace(header) == false) | |
csvdata.AppendLine(header); | |
foreach (var o in objectlist) | |
{ | |
var item = o.ToDictionary(x => x.Key, x => x.Value == null ? string.Empty : x.Value.ToString().Replace(separator, "$")); | |
foreach (var encapsulation in encapsulations) | |
{ | |
if (item.ContainsKey(encapsulation.Key)) | |
{ | |
item[encapsulation.Key] = encapsulation.Value + item[encapsulation.Key]; | |
} | |
} | |
if (string.IsNullOrWhiteSpace(header) == true) | |
{ | |
header = String.Join(separator, item.Select(f => f.Key).ToArray()); | |
csvdata.AppendLine(header); | |
} | |
var row = String.Join(separator, item.Select(f => f.Value).ToArray()); | |
csvdata.AppendLine(row); | |
} | |
return csvdata.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment