2014-12-05 71 views
0

我不太清楚如何做到這一點,但我試圖逐行讀取.CSV文件,將每條獨立行存儲到列表<>中。然後遍歷列表並使用每個項目(行)作爲Employee類的新實例的簽名。C#讀文件行到列表中,並作爲參數使用

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; 
    } 

我的方法庫中存儲類:

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)' 

我的猜測是,它的讀取整條生產線爲我的第一個輸入?有沒有辦法做我想要完成的事情?

回答

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

太棒了,而且會消除其他for-loop。現在它是有道理的,每一行都被當作一個字符串來讀取,所以它當然會被傳遞到第一個參數中。謝謝John,我會閱讀Split()函數。 – 2014-12-05 05:53:11

1

當你構造一個員工時,你正在使用一個你還沒有實現的構造函數。 Employee接受一個字符串,一個字符串和一個int。將這條線解析爲三個預期參數:

foreach (var row in Lines) 
{ 
    var params = row.Split(','); 
    emp.Add(new Employee(params[0], params[1], Convert.ToInt32(params[2]))); 
} 
相關問題