CsvHelper set default custom TypeConverter

前端 未结 3 1443
离开以前
离开以前 2020-12-21 04:05

With CsvHelper, when I want a custom parser (for example, I want a MyBooleanConverter with the input string is \"f\" will be false, \"t\" will

3条回答
  •  清酒与你
    2020-12-21 04:58

    It's also possible to have CsvHelper generate your ClassMap, at which point you can customize its handling for your members. I found this useful for getting things done in my little hobby project.

    var csv = new CsvReader(streamReader, false);
    var classMap = csv.Configuration.AutoMap(); // ClassMap creation
    
    // My price data has dollar signs so those need to be stripped out before parsing to a decimal
    classMap.Map(row => row.Price).ConvertUsing(row => decimal.Parse(row.GetField("Price").Replace("$", "")));
    
    // CsvHelper doesn't support URIs so that requires help as well
    classMap.Map(row => row.Source).ConvertUsing(row => new Uri(row.GetField("Source")));
    
    var prices = csv.GetRecords();
    
    
    
    // my DTO
    class Row
    {
        public decimal Price { get; set; }
        public string ManufacturerSku { get; set; }
        public string Manufacturer { get; set; }
        public Uri Source { get; set; }
        public DateTimeOffset Extraction_Time { get; set; }
    }
    

提交回复
热议问题