Created
May 17, 2019 18:00
-
-
Save JoshClose/1dce4571b535307c87516258f10532ae to your computer and use it in GitHub Desktop.
CsvHelper writing dictionary values
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
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thx