Search code examples
c#csvhelper

Setting column order for CSVHelper


I am using CSVMapper to output the objects within a dictionary:

        using (TextWriter writer = new StreamWriter($"somefile.csv"))
        {
            var csvDP = new CsvWriter(writer);
            csvDP.WriteHeader<NodeDPCount>();
            csvDP.NextRecord();
            foreach (NodeDPCount dpItem in dp.Values)
            {
                csvDP.WriteRecord(dpItem);
                csvDP.NextRecord();
            }
        }

It is a simple class with fields like ID, Name, Age, etc.

However, the output of the columns is in an order I do not like (e.g. ID is not first) and I want to specify which column is first, second, etc.

I believe I have to use the Mapping class, but from the documentation I cannot figure it out. I was hoping for something simple like an annotation to the class, but I guess not.

Can anyone help?

thanks.


Solution

  • Take a look at the Mapping section of the website for CSVHelper (http://joshclose.github.io/CsvHelper/2.x/)

    Specifically:

    When mapping by index you specify the index of the CSV column that that you want to use for that property

    So you'll have to specify a mapping class for your NodeDPCount class, telling it which index to use for which records.

    public sealed class MyNodeDPCountMap : CsvClassMap<NodeDPCount>
    {
        public MyNodeDPCountMap()
        {
            Map( m => m.Id ).Index( 0 );
            Map( m => m.Name ).Index( 1 );
            // etc.
        }
    }
    

    For this to work, you'll need to register your map:

    csv.Configuration.RegisterClassMap<MyNodeDPCountMap>();
    

    Then it will know to use the map you've registered when interacting with the NodeDPCount class