在解析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文档中找到内置特性。我是不是遗漏了什么?
发布于 2014-11-03 11:20:31
我可能会使用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");
});
}
}发布于 2017-06-08 04:45:23
下面是扩展API的解决方案:
public static class CsvHelperExtensions
{
public static CsvPropertyMap Required<T>(this CsvPropertyMap map, string columnName)
{
return map.Name(columnName).ConvertUsing(row =>
{
if (string.IsNullOrEmpty(row.GetField(columnName)))
throw new CsvParserException($"{columnName} is required, but missing from row {row.Row}");
return row.GetField<T>(columnName);
});
}
}用法:
public CsvPersonMap()
{
Map(m => m.FirstName).Required<string>("First");
Map(m => m.LastName).Name("Last");
Map(m => m.MiddleName).Required<string>("Middle");
}发布于 2019-09-11 15:49:19
开发人员现在添加了一个验证方法:https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/validation
使用此方法对非空字符串或空字符串进行验证:
Map(m => m.Id).Validate(field => !string.IsNullOrEmpty(field));
https://stackoverflow.com/questions/26712912
复制相似问题