Home > Blockchain >  how to use ShouldSkipRecord in csvhelper
how to use ShouldSkipRecord in csvhelper

Time:10-17

I have a csv file and i am using csvhelper to read the csv file. The first row is header.

       RowId  Name   --> 0the row
       -----  ----
          1    John
          2    Smith
          3    Mark
          4    Tom

I dont know how to use ShouldSkipRecord for this purpose. How can I directly jump into RowId 3 using CSVHelper ? [do NOT remove header] and starts read from rowid 4 onwards ??

This is what i did.

CsvConfiguration csvConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    HasHeaderRecord = true,
    Delimiter = ",",
    PrepareHeaderForMatch = args => args.Header.ToUpper(),
    IgnoreBlankLines = true,
    IgnoreReferences = true,             
    MissingFieldFound = null,
    UseNewObjectForNullReferenceMembers = true,
    ShouldSkipRecord = row => Convert.ToInt32(row.Row[MyPoint].Skip(0)) <= MyPoint
}; // Mypoint = 3

CsvReader csv = new CsvReader(File.OpenText(FileNameWithPath), csvConfiguration);
csv.Read();

csv.ReadHeader();
while (csv.Read())
{......}

CodePudding user response:

Your ShouldSkip method needs more logic as it needs to deal with the header, the separator and the RowId values. The method needs to return correctly true of false for all of these situations.

Here is one approach to fulfill the requirements:

// row holds an array of string values of each column in the current row
bool ShouldSkipHandler(string[] row)
{
     var rowIdCol = 0;
     // sanitize columnValue
     var currentRowId = row[rowIdCol].Trim();

     // is this the header?
     if (currentRowId == "RowId") {
        return false; 
     }
     // is this the separator
     if (currentRowId.All( c => c == '-')) {
        return true;
     }
     // is this a Rowid
     int rowId;
     if (Int32.TryParse(currentRowId, out rowId)) {
        // is the rowId less than 4? 
        return rowId < 4;
     }
     return true;
}

When put into this test rig:

var sr = new StringReader(@"RowId ,  Name
----- , ----
 1  ,  John
 2  ,  Smith
 3  ,  Mark
 4  ,  Tom
");

var csvConfiguration = new  CsvHelper.Configuration.CsvConfiguration
{
    HasHeaderRecord = true,
    Delimiter = ",",
    ShouldSkipRecord = ShouldSkipHandler
}; 

CsvReader csv = new CsvReader(sr, csvConfiguration);
csv.ReadHeader();
while (csv.Read())
{
    csv[0].Dump(csv.FieldHeaders[0]); // LinqPad
}

and run in LinqPad, this is the result:

showing linqPad output with Header RowId and Value 4

  • Related