Skip to content

Instantly share code, notes, and snippets.

@gazlu
Created July 4, 2015 20:24
Show Gist options
  • Save gazlu/f7b1eef723b8dbeea270 to your computer and use it in GitHub Desktop.
Save gazlu/f7b1eef723b8dbeea270 to your computer and use it in GitHub Desktop.
Simple.Data ResultSet to CSV
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