Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting column order for CSVHelper

Tags:

c#

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.

like image 737
Neil Walker Avatar asked Mar 07 '18 12:03

Neil Walker


2 Answers

You can just use the Index attribute(CsvHelper.Configuration.Attributes.IndexAttribute, Assembly: CsvHelper) instead. here

public class Foo
{
    [Index(0)]
    public int Id { get; set; }

    [Index(1)]
    public string Name { get; set; }
}
like image 51
Tiju John Avatar answered Nov 16 '22 10:11

Tiju John


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

like image 20
simonalexander2005 Avatar answered Nov 16 '22 11:11

simonalexander2005