C#.NET:使用 % 转换器读取 CSV
C#.NET: Read CSV using % converter
我正在读取 CSV 文件
Name,Score
Pat,99%
Chris,87%
并希望在通过 FileHelpers 读取文件时丢弃百分号
using FileHelpers;
public class PctConverter : ConverterBase
{
private NumberFormatInfo nfi = new NumberFormatInfo();
public PctConverter()
{
nfi.PercentSymbol = "%";
}
public override object StringToField(string from)
{
return decimal.Parse(from, NumberStyles.Percent, nfi);
}
}
[DelimitedRecord(",")]
[IgnoreFirst]
public class Student
{
public string Name { get; set; }
public decimal Score { get; set; }
}
var student_file = "students.csv";
var engine = new FileHelperEngine<Student>();
engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
List<Student> students = engine.ReadFileAsList(student_file);
ErrorInfo[] readingErrors = engine.ErrorManager.Errors;
但是我的转换器不太对。你能告诉我为什么吗?
您需要在要转换的字段上指定转换器,而且您的转换器对我不起作用,所以我简化了一点:
public class PctConverter : ConverterBase
{
public override object StringToField(string from)
{
return decimal.Parse(from.Replace("%", ""));
}
}
[DelimitedRecord(",")]
[IgnoreFirst]
public class Student
{
public string Name { get; set; }
[FieldConverter(typeof(PctConverter))]
public decimal Score { get; set; }
}
我正在读取 CSV 文件
Name,Score
Pat,99%
Chris,87%
并希望在通过 FileHelpers 读取文件时丢弃百分号
using FileHelpers;
public class PctConverter : ConverterBase
{
private NumberFormatInfo nfi = new NumberFormatInfo();
public PctConverter()
{
nfi.PercentSymbol = "%";
}
public override object StringToField(string from)
{
return decimal.Parse(from, NumberStyles.Percent, nfi);
}
}
[DelimitedRecord(",")]
[IgnoreFirst]
public class Student
{
public string Name { get; set; }
public decimal Score { get; set; }
}
var student_file = "students.csv";
var engine = new FileHelperEngine<Student>();
engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
List<Student> students = engine.ReadFileAsList(student_file);
ErrorInfo[] readingErrors = engine.ErrorManager.Errors;
但是我的转换器不太对。你能告诉我为什么吗?
您需要在要转换的字段上指定转换器,而且您的转换器对我不起作用,所以我简化了一点:
public class PctConverter : ConverterBase
{
public override object StringToField(string from)
{
return decimal.Parse(from.Replace("%", ""));
}
}
[DelimitedRecord(",")]
[IgnoreFirst]
public class Student
{
public string Name { get; set; }
[FieldConverter(typeof(PctConverter))]
public decimal Score { get; set; }
}