将带有 List<T> 字段的对象写入 CSV

Write an object with a List<T> field to CSV

我正在学习 C# 和对象序列化。我需要将对象保存在 .csv 文件中。我尝试了 CsvHelper 但找不到问题的答案。

假设我有这样一个对象:

public class Record
{
    ...
    public List<string> Collection { get; set; }
    ...
}

如何使用 CsvHelperCollection 的值与其他基本类型一起存储在 .csv 文件的记录中?

默认情况下,

Collection 会被 CsvHelper 忽略。但是,使用 ClassMap 您可以使用 Index 来指示您想要一个简单的 collection 字符串与其他属性一起输出。 (没有很好的记录。)

public class Program
{
    public static void Main(string[] args)
    {
        var records = new List<Record>
        {
            new Record { Id = 1, Name = "Record1", Collection = new List<string>{"First", "Second", "Third"}},
            new Record { Id = 2, Name = "Record2", Collection = new List<string>{"First", "Second"}},
        };

        using (var csv = new CsvWriter(Console.Out))
        {
            csv.Configuration.HasHeaderRecord = false;
            csv.Configuration.RegisterClassMap<RecordMap>();

            csv.WriteRecords(records);
        }

        Console.ReadKey();
    }

}

public class RecordMap : ClassMap<Record>
{
    public RecordMap()
    {
        Map(m => m.Id);
        Map(m => m.Name);
        Map(m => m.Collection).Index(3);
    }
}

public class Record
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<string> Collection { get; set; }
}

输出:

1,Record1,First,Second,Third
2,Record2,First,Second

如果您知道 Collection 中的最大项目数,您还可以设置结束索引并让 CsvHelper 为每个 collection 项目创建标题。

public class RecordMap : ClassMap<Record>
{
    public RecordMap()
    {
        Map(m => m.Id);
        Map(m => m.Name);
        Map(m => m.Collection).Index(3, 5);
    }
}

删除csv.Configuration.HasHeaderRecord = false;,现在它还会为您打印header记录。 输出:

Id,Name,Collection1,Collection2,Collection3
1,Record1,First,Second,Third
2,Record2,First,Second