CSVHelper - Possible to Write List of Dictionary

Viewed 2012

I have a list of Dictionary with same list of keys, but different value. Is there a way to write that to CSV file using the CSVHelper? I have the sample code below, but obviously it didn't work.

       static void Main(string[] args)
        {

            List<Dictionary<String, String>> records = new List<Dictionary<string, string>>();
            Dictionary<String, String> data1 = new Dictionary<String, String>();
            data1.Add("Name1", "Value1");
            data1.Add("Name2", "Value2");
            records.Add(data1);

            Dictionary<String, String> data2 = new Dictionary<String, String>();
            data2.Add("Name1", "Value1");
            data2.Add("Name2", "Value2");
            records.Add(data2);

            using (var writer = new StreamWriter("e:\\temp\\test.csv"))
            using (var csv = new CsvWriter(writer))
            {

                csv.WriteRecords(records);
//GEtting exception here
//CsvHelper.Configuration.CsvConfigurationException: 'Types that inherit IEnumerable cannot be auto mapped. Did you accidentally call GetRecord or WriteRecord which acts on a single record instead of calling GetRecords or WriteRecords which acts on a list of records?'

            }
        }

Is there any way around that?

Thanks!

1 Answers

I believe the only way to do it will be to write them out by hand.

using (var writer = new StreamWriter("e:\\temp\\test.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    var headings = new List<string>(records.First().Keys);

    foreach (var heading in headings)
    {
        csv.WriteField(heading);
    }

    csv.NextRecord();

    foreach (var item in records)
    {
        foreach (var heading in headings)
        {
            csv.WriteField(item[heading]);
        }

        csv.NextRecord();
    }
}

Related