Search code examples
filehelpers

FileHelpers reading a complex csv file including an inner csv list in a class object


I am having a below csv file:

Employer EID,File Creation Date,File Creation Time,Salary Year and Month,Total Salaries,Total Records,,,
1006200,20032016,1031,201603,2200,1,,,
Record ID,Employee QID,Number of Working Days,Net Salary,Basic Salary,Extra hours,Extra Income,Deductions,Payment Type
1,29135617946,31,2200,2200,0,0,0,SALARY 
2,29135617947,31,2200,2300,0,0,0,SALARY 
3,29135617948,31,2200,2250,0,0,0,SALARY 

Above file is having the first part as the employer information and the seond set of rows having the employees working with that along with their salary.

I want to create a complex class Employer which will be having the employees attributes along with a List of complex type named Employee that will include all the employees information.

Please help me by giving a direction/code to how can I achieve this using the FileHelpers.


Solution

  • You can use a MasterDetailEngine. There is an example in the documentation.

    You provide a selector class to enable FileHelpers to determine whether a record is a master record or a detail record.

    private RecordAction ExampleSelector(string record)
    {
        if (record.Length < 2)
            return RecordAction.Skip;
    
        if (IsMasterRecord(record)) // some way of identifying your master records
            return RecordAction.Master;
        else
            return RecordAction.Detail;
    }
    

    Then you can read your the file into your classes like this:

    var engine = new MasterDetailEngine<Employer, Employee>(new MasterDetailSelector(ExampleSelector));
    
    var result = engine.ReadFile("Input.txt");
    
    foreach (var group in result) {
        Console.WriteLine("Customer: {0}", group.Master.EmployerEid);
        foreach (var detail in group.Details)
            Console.WriteLine("    Freight: {0}", detail.EmployeeQid);
    }