【问题标题】:CsvHelper, list the expected header when headers are invalidCsvHelper,当标头无效时列出预期的标头
【发布时间】:2019-07-30 06:03:29
【问题描述】:

使用 CsvHelper 读取 CSV 文件,您可以在 ClassMap 中指定预期的 Header:

public sealed class readFooMapper : ClassMap<FooCSV>
{
    public readFooMapper()
    {
        Map(m => m.Id).ConvertUsing(row => ((CsvReader)row).Parser.Context.RawRow);
        Map(x => x.Foo).Name("Foo");
        Map(x => x.Bar).Name("Bar");
        Map(x => x.FooBar).Name("FooBar");
        Map(x => x.MyOptional).Name("MyOptional").Optional();
    }

}

每个映射的属性都是必需的和预期的,可选的用于区分可能存在或可能不存在的属性。

标头由Action&lt;bool, string[], int, ReadingContext&gt; HeaderValidated 验证,具有各自的参数:isValid、headerNames、headerNameIndex、context。 当一个标题不丢失时,isValid 为假。 headerNames 和 'headerNameIndex' 将分别包含标题的预期名称或索引。 我可以用它来知道缺少标题。

如何访问预期标题列表? ReadingContext context 的许多属性将保存当前标题的列表。

我可以使用验证循环将所有 headerNames 和 'headerNameIndex' 添加到列表中。

var errorSb = new StringBuilder();
[...]
csvReader.Configuration.HeaderValidated =
    (isValid, headerNames, headerNameIndex, context) =>
    {
        allHeaderNames.Add(headerNames);
        if (!isRowValid)
        {
            isHeaderInvalid= true;
        }
    };

我真正想要的是readFooMapper 映射配置。
告诉用户:“看,我期望这个列列表:##、##、##。带有这些可选列:X、Y、Z。\n 缺少列 = A、B、C。”

这无需维护一个另一个列表标题和可选。

【问题讨论】:

    标签: c# csvhelper


    【解决方案1】:

    我认为这与您正在寻找的内容很接近。它不会检查您的 ConvertUsing 方法中是否引用了列。

    var map = new readFooMapper();
    
    var required = map.MemberMaps
                      .Where(m => m.Data.Ignore == false 
                               && m.Data.ReadingConvertExpression == null 
                               && m.Data.IsOptional == false)
                      .Select(m => m.Data.Member.Name)
                      .ToList();
    var optional = map.MemberMaps
                      .Where(m => m.Data.Ignore == false 
                               && m.Data.ReadingConvertExpression == null 
                               && m.Data.IsOptional == true)
                      .Select(m => m.Data.Member.Name)
                      .ToList();
    

    【讨论】:

    • 太棒了。我正在查看上下文中的每个对象,但 MemberMaps 正是我需要的。这不仅仅是关闭。
    • 请注意,ConvertUsing 可能会通过引用未以其他方式映射的列来破坏事物。
    猜你喜欢
    • 2016-02-26
    • 1970-01-01
    • 2018-01-28
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2012-08-06
    • 2019-05-13
    相关资源
    最近更新 更多