最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use generate a line number with CsvHelper for a record type - Stack Overflow

programmeradmin0浏览0评论

I have a record type, for example:

public record TestCsvRecord(string StringValue1, string StringValue2, int LineNumber);

and a CSV file without a line number column

StringValue1,StringValue2
Hello,World
Hello,Europe
Bonjour,Monde

I see from elsewhere that I should be mapping the LineNumber field using .Convert(record => record.Row.Parser.RawRow) like so:

public class TestCsvRecordMap : ClassMap<TestCsvRecord>
{
    public TestCsvRecordMap()
    {
        this.AutoMap(CultureInfo.InvariantCulture);

        this.Map(x => x.LineNumber)
            .Convert(record => record.Row.Parser.RawRow);
    }
}

A simple test to use this is:

string csvData = "StringValue1,StringValue2\nHello,World\nHello,Europe\nBonjour,Monde";

CsvConfiguration defaultConfiguration = new(CultureInfo.InvariantCulture)
{
    HasHeaderRecord = true,
    MissingFieldFound = null,
    HeaderValidated = null,
};

StringReader reader = new(csvData);
using var csv = new CsvReader(reader, defaultConfiguration);

csv.Context.RegisterClassMap<TestCsvRecordMap>();

var records = csv.GetRecords<TestCsvRecord>().ToList();
Assert.Equal(3, records.Count(x => x.LineNumber > 1));

But when I try to use this class map I get a System.ArgumentException : Incorrect number of arguments for constructor error. I have tried to Ignore() the column, Parameter() mapping, setting it to Optional().

发布评论

评论列表(0)

  1. 暂无评论