Skip to content

Instantly share code, notes, and snippets.

@JoshClose
Created May 17, 2019 18:00
Show Gist options
  • Save JoshClose/1dce4571b535307c87516258f10532ae to your computer and use it in GitHub Desktop.
Save JoshClose/1dce4571b535307c87516258f10532ae to your computer and use it in GitHub Desktop.
CsvHelper writing dictionary values
void Main()
{
var records = new List<Dictionary<string, string>>
{
new Dictionary<string, string> { { "Id", "1" }, { "Name", "one" } },
new Dictionary<string, string> { { "Id", "2" }, { "Name", "two" } }
};
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer))
{
var hasHeaderBeenWritten = false;
foreach (var row in records)
{
if (!hasHeaderBeenWritten)
{
foreach (var pair in row)
{
csv.WriteField(pair.Key);
}
hasHeaderBeenWritten = true;
csv.NextRecord();
}
foreach (var pair in row)
{
csv.WriteField(pair.Value);
}
csv.NextRecord();
}
writer.ToString().Dump();
}
}
@NiakmaJr
Copy link

thx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment