c# - Reading CSV with optional column using CsvHelper
问题描述
I want to read a CSV file that has some optional columns, for that I have defined a class with optional property using "?" but can't make it work.
public class MyItem
{
public int Id { get; set; }
public int? MyValue { get; set; }
}
The mapping class:
public sealed class MyItemMap : ClassMap<MyItem>
{
public MyItemMap()
{
Map(m => m.Id);
Map(m => m.MyValue);
}
}
And then a console app:
static void Main(string[] args)
{
using (var reader = new StreamReader(@"C:\Test2Delete\ConsoleAppCSV\MyItem.csv"))
using (var csv = new CsvReader(reader))
{
csv.Configuration.RegisterClassMap(new MyItemMap());
csv.Configuration.HeaderValidated = null;
try
{
var records = csv.GetRecords<MyItem>();
foreach (var r in records)
{
Console.WriteLine(r.Id + " " + r.MyValue);
}
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
}
So I want to be able to read files that contain "Id", "MyValue" columns and also files with only "Id" column. How can I achieve this?
解决方案
设置MyValue
为可选。
public sealed class MyItemMap : ClassMap<MyItem>
{
public MyItemMap()
{
Map(m => m.Id);
Map(m => m.MyValue).Optional();
}
}
推荐阅读
- python - 带有 Radiobutton 的 Python tkinter 动态输入框
- python - 从文本字段小部件中获取所有值并将它们返回到按钮小部件
- apache-spark - SPARK java.lang.OutOfMemoryError:没有足够的内存来构建表并将表广播到所有工作节点
- nativescript - Radlist 查看可折叠项目动画
- android - AnySoftKeyboard:将语言包集成到 apk 中,无需使用插件
- perforce - 在命令行中创建时如何保存更改列表编号?
- python - / (Divison) 运算符在 numpy 数组中做了什么?
- python - 如何使用反斜杠 Python
- android - 是否可以使用 xamarin 表单将面板滑块作为真正的 android 系统滑块拖动到下面板?
- c# - (ASP.NET MVC5) 文件应该如何保存?在 SQL Server 数据库或服务器文件夹中,哪种解决方案更适合这些情况?