简体   繁体   中英

How to read in tree (parent-child) from flat CSV data?

I have a class Employee :

public class Employee
{
    public Employee()
    {       
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public Employee Manager { get; set; }
}

and a csv file wich contain all the employees, 1st part of a line is the Id, 2nd part is the name, and the 3rd part is the Id of the manager, if it's a empty then the employee doesn't have a manager :

2;John;1    
1;James;    
3;Linda;1

I created a class CsvReader, in this class I have a method GetEmployees, the problem is that I cannot assign a value to the property Manager !

...
 var lines = File.ReadAllLines(this.FilePath);
 foreach (var line in lines)
 {
 var parts = line.Split(';');
 var emp = new Employee();
 emp.Id = int.parse(parts[0]);
 emp.Name = parts[1];
 emp.Manager = ????
 }
 return employees;
}

I hope that the problem is clear

This can be solved using these steps:

  1. Read in all the records; store the Manager Id (but don't assign a Manager value). For simplicity simple add another property to the Employee type.

  2. After creating an Employee object add it to a Dictionary<int,Employee> where the key is the Employee ID.

  3. After reading in all records, loop through the dictionary of Employees (the order does not matter), and for each Employee assign the Manager value. (The Manager Employee object is employeeDict[employee.ManagerId] .)

Create a Dictionary<int, Employee> , store mapping between employees Id and Employee class instance representing that employee and use it to get reference to manager:

var lines = File.ReadAllLines(this.FilePath);
var mapping = new Dictionary<int, Employee>();
foreach (var line in lines)
{
    var parts = line.Split(';');
    var emp = new Employee();
    emp.Id = int.parse(parts[0]);
    emp.Name = parts[1];
    if(!string.NullOrEmpty(parts[2]))
        emp.Manager = mapping[int.Parse(parts[2])];

    mapping[emp.Id] = emp;
}

It's not bulletproof, and it requires that data in CSV is correct:

  • there is no employee with ManagerId pointing to non-existing manager
  • manager must be declared in the file before all his reports

But it should give you an idea of how to solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM