Search code examples
c#csvstreamreaderilist

C# read file line into List and use as parameters


I'm not quite sure how to do this, but I am trying to read a .CSV file line-by-line storing each independent line into a List<>. Then loop through the list and use each item (row) as a signature for a new instance of my Employee class.

database.csv

John Doe,4568,0
Jane Smith,6154,1   // this represents my constructors signature
...
...

Employee.cs (constructor only)

public Employee(string emp, string id, int state)
    {
        EmpName = emp;
        IdName = id;
        _empState = state;
    }

my method in a Repository class:

public IList<Employee> getListOfActiveEmployees()
    {

        string filePath = @"(filepath)\database.csv";

        var emp = new List<Employee>();

        //var LogFile = File.ReadAllLines(filePath);

        List<string> Lines = new List<string>();
        using (var sr = new StreamReader(filePath))
        {
            while (sr.Peek() >= 0)
            {
                Lines.Add(sr.ReadLine());
            }
        }

        foreach (var row in Lines)
        {
            emp += new Employee(row);
        }

        return emp;
    }

Error:

Error   CS7036  There is no argument given that corresponds to the required 
formal parameter 'id' of 'Employee.Employee(string, string, int)'

My guess is that it's reading the whole line as my first input? Is there a way to do what I am trying to accomplish?


Solution

  • You need to split the string so you can distribute it on the parameters of the constructor.

    while (sr.Peek() >= 0)
    {
        string line = sr.ReadLine(); // store the value in a variable
        if (!String.IsNullOrWhiteSpace(line)) // check if not empty
        {
            string[] val = line.Split(','); // assuming it returns three values
    
            // you can add extra validation here
            // array should have 3 values
            // otherwise it will throw invalid index exception
            emp.Add(new Employee(val[0], val[1], Convert.ToInt32(val[2])));
        }
    }
    
    return emp;