我不太确定如何做到这一点,但我正在尝试逐行读取.CSV文件,将每条独立行存储到List<>中。然后遍历列表并使用每个项目(行)作为我的Employee类的新实例的签名。
database.csv
John Doe,4568,0
Jane Smith,6154,1 // this represents my constructors signature
...
...
Employee.cs (仅限构造函数)
public Employee(string emp, string id, int state)
{
EmpName = emp;
IdName = id;
_empState = state;
}
我在Repository类中的方法:
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 CS7036 There is no argument given that corresponds to the required
formal parameter 'id' of 'Employee.Employee(string, string, int)'
我的猜测是它正在阅读整行作为我的第一个输入?有没有办法做我想要完成的事情?
答案 0 :(得分:2)
您需要拆分字符串,以便将其分布在构造函数的参数上。
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;
答案 1 :(得分:1)
构建员工时,您正在使用尚未实现的构造函数。 Employee接受字符串,字符串和int。将该行解析为三个预期参数:
foreach (var row in Lines)
{
var params = row.Split(',');
emp.Add(new Employee(params[0], params[1], Convert.ToInt32(params[2])));
}