2012-06-29 168 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);