CSVHelper必填字段

道格144

解析CSV文件时,如何定义特定字段为必填字段。本质上,我想确保给定的字段永远不会为空,如果是,那么我想抛出一个异常。这是映射类:

public sealed class DataMapper : CsvClassMap<DataType>
{
    public DataMapper()
    {
        Map(m => m.Field1).Name("FirstField");
        Map(m => m.Field2).Name("SecondField");
        Map(m => m.Field3).Name("ThirdField"); // this field should be mandatory
    }
}

和用法:

List<DataType> data;
using (var sr = new StreamReader(localFilePath))
{
    var reader = new CsvReader(sr);
    reader.Configuration.RegisterClassMap<DataMapper>();
    data = reader.GetRecords<DataType>().ToList();
}

目前,我只是在检查数据列表中的结果,如下所示:

var numberOfInvalidRecords = data.Count(data => string.IsNullOrEmpty(data.Field3));
if (nullAccountHolderRecords > 0)
{
    //handle
}

我无法在CSVHelper文档中找到内置功能。我想念什么吗?

戴维

我可能会使用ConvertUsing扩展名执行此操作

public sealed class DataMapper : CsvClassMap<DataType>
{
    public DataMapper()
    {
        Map(m => m.Field1).Name("FirstField");
        Map(m => m.Field2).Name("SecondField");
        Map(m => m.Field3).ConvertUsing(row =>
        {
            if(string.IsNullOrEmpty(row.GetField<string>("ThirdField")))
                throw new Exception("Oops, ThirdField is empty!");
            return row.GetField<string>("ThirdField");
        });
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章