2012-06-29 60 views
0

你好傢伙我正在閱讀一個本地csv文件至極有數據,我最終將使用加載到數據庫。我的問題很簡單,但我似乎無法理解這個概念。以下是我的代碼。很簡單的東西。不能將字符串添加到字符串c的列表#

 static void loadTables() { 
     int size = new int(); 
     string[] empid = new string[0]; 

     //string[] empid = new string(); 
     List<string[]> EmployeeName = new List<string[]>(); 
     List<string[]> EmployeeId = new List<string[]>(); 
     List<string[]> Group = new List<string[]>(); 
     List<string[]> Org = new List<string[]>(); 
     List<string[]> Fund = new List<string[]>(); 
     try { 
      using (StreamReader readFile = new StreamReader("C:\\temp\\groupFundOrgReport.csv")) 
      { 
      string line; 
       string[] row; 
       size = 0; 
       while ((line = readFile.ReadLine()) != null) 
       { 
        row = line.Split(','); 
        /*resize the array up by 1*/ 
        Array.Resize(ref empid,empid.Length+1); 
        /*im using size as a counter to add to the slot on the array.*/ 
        empid[size] = row[0].Remove(0,1); 
        // here i reciever error (the best overload match of system generic list?...etc) 
        EmployeeName.Add(row[0]); 
        size++; 

       } 

      } 
      } 

     catch(Exception e){ 

      Console.WriteLine(e); 

     } 




    } 

我有一個字符串列表,但任何嘗試向它添加一個字符串都會給我一個錯誤。換句話說,如果我嘗試這樣做EmployeeName.Add(row [0] .ToString);我收到一個錯誤。但是,如果我評論線,我可以使用舊的時尚陣列。我真的很喜歡使用列表,但我似乎無法傳遞我想要的值。有人可以請我指出正確的方向。

在此先感謝 米格爾

+0

我自己也嘗試** EmployeeName.Add(行[0]); **,沒有運氣 – Miguel

+0

是不是行[0]單字符串 - 不是一個字符串[]? –

+0

錯誤'System.Collections.Generic.List .Add(string [])'的最佳重載方法匹配有一些無效參數 – Miguel

回答

2

我從您的代碼中猜測,員工姓名是CSV文件的第一個字段。

您已將EmployeeName聲明爲字符串數組列表List<string[]>,而不是字符串列表List<string>

行[0]是數組中的第一個字符串,所以您試圖將字符串添加到希望添加字符串數組的列表中。

你應該只聲明EmployeeName作爲List<string>,用這樣一行:

List<string> EmployeeName = new List<string>(); 

var EmployeeName = new List<string>(); 
+0

我現在明白了。當我嘗試使用的是字符串列表時,我正在使用數組列表。我覺得自己像一個真正的大白癡。原諒我的noobness。感謝您的迴應。 – Miguel

+0

@Miguel - 沒問題。樂意效勞。 – iandotkelly

2

你的問題是EmployeeName的聲明,這是stringList陣列:

List<string[]> EmployeeName = new List<string[]>(); 

將其更改爲:

var EmployeeName = new List<string>(); 

或者,使用List<string[]>相應...

2

EmployeeNameList<string[]>,所以你必須寫:

EmployeeName.Add(row); 

在分割字符串時刪除空條目使用方法:

row=line.Split(New String() {","}, 
        StringSplitOptions.RemoveEmptyEntries); 
1

他們都是List S 'String Array的S'

List<string[]> EmployeeName = new List<string[]>(); 
List<string[]> EmployeeId = new List<string[]>(); 
List<string[]> Group = new List<string[]>(); 
List<string[]> Org = new List<string[]>(); 
List<string[]> Fund = new List<string[]>(); 

您可以添加唯一的變量會像

//Define array of strings 
var strArr = new string[] {"abc", "xyz"}; 

,那麼你可以調用

EmployeeName.Add(strArr); 

雖然改變List泛型類型來string類型將解決您的問題

List<string> EmployeeName = new List<string>(); 
List<string> EmployeeId = new List<string>(); 
List<string> Group = new List<string>(); 
List<string> Org = new List<string>(); 
List<string> Fund = new List<string>(); 

var str = "My String"; 

EmployeeName.Add(str);