设置 CSVHelper 的列顺序
Setting column order for CSVHelper
我正在使用 CSVMapper 输出字典中的对象:
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();
}
}
这是一个简单的 class,包含 ID、姓名、年龄等字段
但是,列的输出顺序我不喜欢(例如 ID 不是第一个),我想指定哪个列是第一个,第二个等等
我想我必须使用映射 class,但从文档中我无法弄清楚。我希望有一些简单的东西,比如 class 的注释,但我想不会。
有人能帮忙吗?
谢谢。
查看 CSVHelper
(http://joshclose.github.io/CsvHelper/2.x/)
网站的映射部分
具体来说:
When mapping by index you specify the index of the CSV column that that you want to use for that property
因此您必须为 NodeDPCount
class 指定一个映射 class,告诉它哪个索引用于哪些记录。
public sealed class MyNodeDPCountMap : CsvClassMap<NodeDPCount>
{
public MyNodeDPCountMap()
{
Map( m => m.Id ).Index( 0 );
Map( m => m.Name ).Index( 1 );
// etc.
}
}
为此,您需要注册您的地图:
csv.Configuration.RegisterClassMap<MyNodeDPCountMap>();
然后它会知道在与 NodeDPCount
class
交互时使用您注册的地图
您可以只使用 Index 属性(CsvHelper.Configuration.Attributes.IndexAttribute,程序集:CsvHelper)。 here
public class Foo
{
[Index(0)]
public int Id { get; set; }
[Index(1)]
public string Name { get; set; }
}
我正在使用 CSVMapper 输出字典中的对象:
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();
}
}
这是一个简单的 class,包含 ID、姓名、年龄等字段
但是,列的输出顺序我不喜欢(例如 ID 不是第一个),我想指定哪个列是第一个,第二个等等
我想我必须使用映射 class,但从文档中我无法弄清楚。我希望有一些简单的东西,比如 class 的注释,但我想不会。
有人能帮忙吗?
谢谢。
查看 CSVHelper
(http://joshclose.github.io/CsvHelper/2.x/)
具体来说:
When mapping by index you specify the index of the CSV column that that you want to use for that property
因此您必须为 NodeDPCount
class 指定一个映射 class,告诉它哪个索引用于哪些记录。
public sealed class MyNodeDPCountMap : CsvClassMap<NodeDPCount>
{
public MyNodeDPCountMap()
{
Map( m => m.Id ).Index( 0 );
Map( m => m.Name ).Index( 1 );
// etc.
}
}
为此,您需要注册您的地图:
csv.Configuration.RegisterClassMap<MyNodeDPCountMap>();
然后它会知道在与 NodeDPCount
class
您可以只使用 Index 属性(CsvHelper.Configuration.Attributes.IndexAttribute,程序集:CsvHelper)。 here
public class Foo
{
[Index(0)]
public int Id { get; set; }
[Index(1)]
public string Name { get; set; }
}