如何使用 CSVHelper 在 CSV 中写入类的列表属性
目前我有以下类结构
class Foo{
int FooID {get;set;}
List<Bar> Bars {get;set;};
}
class Bar{
int BarID {get;set;}
string BarProperty1 {get;set;}
string BarProperty2 {get;set;}
string BarProperty3 {get;set;}
}
现在我想编写一个 CSV 文件,其中有一个字段“ID”,它是 Foo 的 ID 和 Bars ID 的混合,其余的应该是 Bar 对象的属性。
这是一些示例对象:
Foo01 ID = 01
List bars = {A, Red, Red, Green; B, Yellow, Red, Red}
Foo02 ID = 02
List bars = {A, Green, Green, Red; B, Red, Purple, Orange; C, White, Black, Red}
现在 CSV 编写器应该创建一个如下所示的 CSV:
ID;Prop1;Prop2;Prop3
01A;Red;Red;Green
01B;Yellow;Red;Red
02A;Green;Green;Red
02B;Red;Purple;Orange
02C;White;Black;Red
这可以通过 CSVHelper 实现吗?还是我需要编写自己的实现?
Currently I have the following class structures
class Foo{
int FooID {get;set;}
List<Bar> Bars {get;set;};
}
class Bar{
int BarID {get;set;}
string BarProperty1 {get;set;}
string BarProperty2 {get;set;}
string BarProperty3 {get;set;}
}
Now I want to write a CSV file which has a field "ID" which is a mix between the ID of the Foo and Bars ID and the rest should be the properties of the Bar object.
This are some example objects:
Foo01 ID = 01
List bars = {A, Red, Red, Green; B, Yellow, Red, Red}
Foo02 ID = 02
List bars = {A, Green, Green, Red; B, Red, Purple, Orange; C, White, Black, Red}
Now the CSV writer should create a CSV looking like this:
ID;Prop1;Prop2;Prop3
01A;Red;Red;Green
01B;Yellow;Red;Red
02A;Green;Green;Red
02B;Red;Purple;Orange
02C;White;Black;Red
Is this possible with the CSVHelper or do I need to write my own implementation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
遗憾的是,您无法直接从单个对象创建多个 CSV 行。因此,您必须整理列表并将其写入 CSV 文件。
这是一个工作示例:
Unfortunately you can not directly create multiple CSV lines from a single object. So you have to flatten your list and write these into a CSV file.
Here is a working example:
您只需要 writer 对象和嵌套的 for 循环。
You only need the writer object and for-loop nested.
我找到了一种更简单、更简单的做事方法:
我基本上创建了一个名为 CSVEntry 的新类,具有所需的属性,并循环遍历我的对象以生成所需的条目,然后使用 CSVHelper 将它们写入文件。
I have found a much easier and less complicated way of doing things:
I basically created a new Class called CSVEntry with the required properties and looped trough my opjects to generate the desired entry before writing them to a file with CSVHelper.