2011-03-18 109 views
1

我有这种方法,并得到上述错误的行words.Add(rows);谁能帮忙?谢谢 - 奔C#无法从字符串[]转换为字符串

private static IEnumerable<string> LoadWords(String filePath) 
    { 

     List<String> words = new List<String>(); 

     try 
     { 
      foreach (String line in File.ReadAllLines(filePath)) 
      { 
       string[] rows = line.Split(','); 

       words.Add(rows); 
      } 

     } 
     catch (Exception e) 
     { 
      System.Windows.MessageBox.Show(e.Message); 
     } 

      return words; 
    } 
+0

列表为了你自己的信息,[这里](http://stackoverflow.com/questions/3891157/an-i-使用通用限制/ 3891439#3891439)Eric Lippert解释了为什么“添加”和“添加范围”是分开的功能。 [这里](http://stackoverflow.com/questions/3891157/an-i-prevent-a-specific-type-using-generic-restrictions/3891584#3891584)LBushkin进入更多的细节,看着技术限制,使这种选择必要。如果没有这些技术限制,拥有两个独立的功能仍然是一个好主意。 – Brian 2011-03-18 17:38:01

回答

6

而不是

words.Add(rows); 

使用本:

words.AddRange(rows); 

rows是包含多个字符串的字符串数组,所以你必须向他们AddRange()添加。

4

改成这样

words.AddRange(rows); 

您的问题是,您要添加的项目的数组,而不是一个单一的元素。

您使用的AddRange()将实现这里System.Collections.Generic.IEnumerable<T>

查看文档http://msdn.microsoft.com/en-us/library/z883w3dc.aspx

0

您使用了错误的方法集合时。你需要AddRange方法。

words.AddRange(rows); 
0

有这样的尝试:

words.AddRange(rows); 
1

您正在尝试一个字符串数组添加到需要一个字符串列表。

尝试words.AddRange(rows);

0

.Add将采取另一个字符串,而不是字符串数组。

尝试用.AddRange代替。

0
private static IEnumerable<string> LoadWords(String filePath) 
{ 

    List<String> words = new List<String>(); 

    try 
    { 
     foreach (String line in File.ReadAllLines(filePath)) 
     { 
      string[] rows = line.Split(','); 

      foreach (String word in rows) 
      { 
       words.Add(word); 
      } 
     } 

    } 
    catch (Exception e) 
    { 
     System.Windows.MessageBox.Show(e.Message); 
    } 

     return words; 
} 
+0

+0:这会起作用,但只是调用'AddRange'比'foreach'更清洁。 – Brian 2011-03-18 17:39:07

+0

我同意,但如果OP需要查看排除某些单词的方法,则可以让他在插入前看到添加一段代码以进行测试。 – jp2code 2011-03-18 19:15:00

0

乌尔尝试添加阵列的字符串数组

private static IEnumerable<string> LoadWords(String filePath) 
    { 

     List<String> words = new List<String>(); 

     try 
     { 
      foreach (String line in File.ReadAllLines(filePath)) 
      { 
       string[] rows = line.Split(','); 

       foreach(string str in rows) 
         words.Add(str); 
      } 

     } 
     catch (Exception e) 
     { 
      System.Windows.MessageBox.Show(e.Message); 
     } 

      return words; 
    }