The dictionary is not supported, but ExpandoObject is supported.
https://github.com/JoshClose/CsvHelper/blob/48e70742e06007dae3a635c418b7e3358f667c4f/src/CsvHelper.Tests/Writing/MultipleHeadersTest.cs
https://github.com/JoshClose/CsvHelper/blob/b74a2f95a101158f4cdedd25fae6e8392b58855b/src/CsvHelper.Tests/Writing/DynamicTests.cs
If you follow the first link above, you will find the WriteDynamicHeader method used on lines 50 and 57.
Using the extension method, I create an ExpandoObject for each record and use CsvHelper to write this object. The Dictionary<string, object>
parameter named document
is what I want to create a CSV record.
public static class DictionaryCsvExtentions { public static dynamic BuildCsvObject(this Dictionary<string, object> document) { dynamic csvObj = new ExpandoObject(); foreach (var p in document) { AddProperty(csvObj, p.Key, p.Value); } return csvObj; } private static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue) { var expandoDict = expando as IDictionary<string, object>; if (expandoDict.ContainsKey(propertyName)) { expandoDict[propertyName] = propertyValue; } else { expandoDict.Add(propertyName, propertyValue); } } }
Now I can create an ExpandoObject from my dictionary like this
var csvObj = myDictonary.BuildCsvObject();
and yet, after the Josh tests in the link above, we have everything we need to use the dictionary pretty easily with CsvHelper. I don't think this is the best solution for Michael, just a different approach.
loan, for which the basic ExpandoObject from the dictionary code should be provided (there is much more explanation here!) https://www.oreilly.com/learning/building-c-objects-dynamically
source share