CsvHelper 映射问题

CsvHelper mapping issue

我有一个与 CsvHelper 库相关的问题,我不知道如何将 csv 文件映射到以下 MyClass 对象。 csv 文件如下所示:

id, Property1, property2....
1, x, a,b,c
2,x, d,f
3, y, g,h,i,j,k 
...

我想将其解析为以下 类

public class MyClass
{
    public string Id { get; set; }

    public List<Custom> MyCustoms { get; set; }
}

public class Custom
{
    public string Property1 { get; set; }

    public List<string> Property2 { get; set; }
}

ConvertUsing 将是最简单的映射方式。

public class Program
{
    static void Main(string[] args)
    {
        using (var stream = new MemoryStream())
        using (var writer = new StreamWriter(stream))
        using (var reader = new StreamReader(stream))
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            writer.WriteLine("Id,Property1,Property2,Property3,Property4,Property5,Property6");
            writer.WriteLine("1,x,a,b,c");
            writer.WriteLine("2,x,d,f");
            writer.WriteLine("3,y,g,h,i,j,k");
            writer.Flush();
            stream.Position = 0;

            var test = csv.Configuration.RegisterClassMap<MyClassMap>();

            var records = csv.GetRecords<MyClass>().ToList();
        } 
    }
}

public class MyClassMap: ClassMap<MyClass>
{
    public MyClassMap()
    {
        Map(m => m.Id);
        Map(m => m.MyCustoms).ConvertUsing(row =>
        {
            var custom = new Custom 
            { 
                Property1 = row["Property1"], 
                Property2 = new List<string>() 
            };

            var index = 2;

            while (row.TryGetField(typeof(string), index, out var property))
            {
                custom.Property2.Add((string)property);
                index++;
            }

            return new List<Custom> { custom };
        });
    }
}

public class MyClass
{
    public string Id { get; set; }

    public List<Custom> MyCustoms { get; set; }
}

public class Custom
{
    public string Property1 { get; set; }

    public List<string> Property2 { get; set; }
}