Setting column order for CSVHelper

谁都会走 提交于 2020-06-27 07:41:24

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/49152554/setting-column-order-for-csvhelper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!