【问题标题】:CsvHelper define custom mapping for a columnCsvHelper 为列定义自定义映射
【发布时间】:2020-04-05 02:48:48
【问题描述】:

我正在尝试使用 CSVHelper 填充 CSV 文件中未提供的列。 这是我需要导入的 CSV 示例

Id
10
123
45
213

我要反序列化的类是这个:

public class Foo {
    public int Id { get; set }
    public string Name { get; set }
}

使用默认配置我得到这个错误:

CsvHelper.HeaderValidationException:找不到名为“名称”的标题。

我希望能够定义一个映射器,以便解析器可以填充列Name(例如,通过提供值字典)。有什么办法吗?

谢谢

--------- 编辑

澄清一下,这个想法是有一个类似于转换器的东西,它与一个字段相关联,用于将 Id 解码为名称

public class NameConverter
{
    public NameConverter()
    {
        employeesList = new Dictionary<int, string>()
        {
            { 10, "Mary" },
            { 45, "Mike" },
            { 123, "Jack" },
            { 213, "Suzanne" },
        };
    }

    IDictionary<int, string> employeesList;

    public string GetValue(int id) => employeesList[id];
}

我想,另一种方法是按照建议忽略 Name 字段,并将 NameConverter 注入 Foo 类中,并使 Name 成为只能获取的属性。

【问题讨论】:

  • 我不明白你的意思是 Name 的值字典。当我理解时,我可以添加到我的答案中。
  • @JoshClose,用于解码 id 的值字典,例如一个员工列表,这样你就可以知道 10 是“Mary”,123 是“Jack”,45 是“Mike”等等。在我的应用程序中,它们可能来自数据库表。

标签: c# csvhelper


【解决方案1】:
void Main()
{
    var s = new StringBuilder();
    s.AppendLine("Id");
    s.AppendLine("45");
    s.AppendLine("123");
    using (var reader = new StringReader(s.ToString()))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        csv.Configuration.RegisterClassMap<FooMap>();
        csv.GetRecords<Foo>().ToList().Dump();
    }
}

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class FooMap : ClassMap<Foo>
{
    public FooMap()
    {
        var nameConverter = new NameConverter();
        Map(m => m.Id);
        Map(m => m.Name).ConvertUsing(row => nameConverter.GetValue(row.GetField<int>(nameof(Foo.Id))));
    }
}

public class NameConverter
{
    public NameConverter()
    {
        employeesList = new Dictionary<int, string>()
        {
            { 10, "Mary" },
            { 45, "Mike" },
            { 123, "Jack" },
            { 213, "Suzanne" },
        };
    }

    IDictionary<int, string> employeesList;

    public string GetValue(int id) => employeesList[id];
}

输出:

【讨论】:

  • 我添加了更多信息,希望它能阐明目的!
  • 啊!转换使用。那太棒了!非常感谢!
猜你喜欢
  • 2022-01-11
  • 2017-02-17
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
相关资源
最近更新 更多