binary robot
binary robot

Reputation: 83

How to take not valid lines from csv-file?

I use TinyCsvParser as tool to map lines from large csv-file into my data models. So, the question is how I can take not a valid lines to display it for user? Now it works with Regex, but I gonna re-write it on more readable tool. Is it possible?(Now I can change TinyCsvParser to any other tool, that pretty fast to process the large csv-files and has readable api).

Now it seems like: Model:

public class Item
{
    public string Id { get; set; }
    public string Description { get; set; }
    public string Country { get; set; }
    public string Time { get; set; }
    public string ErrorDescription { get; set; }

    public override string ToString()
        => $"{Id } {Description } {Country} {Time} {ErrorDescription}";
}

Parser:

public class CsvItemMapping : CsvMapping<Item>
    {
        public CsvItemMapping()
            : base()
        {
            MapProperty(columnIndex: 0, x => x.Id);
            MapProperty(columnIndex: 1, x => x.Description );
            MapProperty(columnIndex: 2, x => x.Country);
            MapProperty(columnIndex: 3, x => x.Time);
            MapProperty(columnIndex: 4, x => x.ErrorDescription);
        }
    }

Code to parse:

// this is selects ONLY valid lines, that parser mapped to models.
// I want a flag like "Not valid" and display it at the time, when read this line             
    var csvParserOptions = new CsvParserOptions(skipHeader: true, fieldsSeparator: ',');
    var csvMapper = new CsvItemMapping();
    var csvParser = new CsvParser<Item>(csvParserOptions, csvMapper);
    
    const string path = @"...";
    var result = csvParser
        .ReadFromFile(path, Encoding.UTF8)
        .Select(x => x.Result)
        .ToList();

Upvotes: 0

Views: 235

Answers (0)

Related Questions