首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CsvHelper映射问题

CsvHelper映射问题
EN

Stack Overflow用户
提问于 2020-07-24 22:45:40
回答 1查看 91关注 0票数 0

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

代码语言:javascript
复制
id, Property1, property2....
1, x, a,b,c
2,x, d,f
3, y, g,h,i,j,k 
...

我想把它解析成下面的类

代码语言:javascript
复制
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; }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-29 03:17:21

ConvertUsing将是映射这一点的最简单的方法。

代码语言:javascript
复制
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; }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63075975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档