【问题标题】:CsvHelper mapping issueCsvHelper 映射问题
【发布时间】:2020-07-24 14:45:40
【问题描述】:

我有一个与 CsvHelper 库相关的问题,我不知道如何将 csv 文件映射到以下 Mycalss 对象。 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; }
}

【问题讨论】:

    标签: csv parsing csvhelper


    【解决方案1】:

    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; }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-12
      • 2022-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多