[英]cant add string to list of string c#
大家好,我正在讀取具有數據的本地csv文件,最終我將用它來加載到數據庫中。 我的問題本質上很簡單,但我似乎無法掌握這個概念。 下面是我的代碼。 很簡單的東西。
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); 我得到一個錯誤。 但是,如果我注釋掉行,則可以使用舊的時尚數組。 我真的很喜歡使用列表,但是我似乎無法傳遞所需的值。 有人能指出我正確的方向嗎?
在此先感謝Miguel
您的問題是EmployeeName
的聲明,它是string
數組的List
:
List<string[]> EmployeeName = new List<string[]>();
更改為:
var EmployeeName = new List<string>();
或者,相應地使用List<string[]>
...
我從您的代碼中猜測員工名稱是CSV文件的第一字段。
您已將EmployeeName聲明為字符串List<string[]>
的數組List<string[]>
,而不是字符串List<string>
。
Row [0]是數組中的第一個字符串,因此您嘗試將字符串添加到希望添加字符串數組的列表中。
您應該使用以下行將EmployeeName聲明為List<string>
:
List<string> EmployeeName = new List<string>();
要么
var EmployeeName = new List<string>();
EmployeeName
是一個List<string[]>
因此您必須編寫:
EmployeeName.Add(row);
要在拆分字符串時刪除空條目,請使用:
row=line.Split(New String() {","},
StringSplitOptions.RemoveEmptyEntries);
它們都是String Array
的List
。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.