【问题标题】:Adding string array (string[]) to List<string> c#将字符串数组 (string[]) 添加到 List<string> c#
【发布时间】:2012-10-04 16:02:56
【问题描述】:

当 string[], _lineParts 添加到 List 中时,我在 List 中看到的只是“System.String[]” 需要做什么才能看到列表中实际的 string[] 值。

while (_aLine != null) 
{ 
    //split the line read into parts delimited by commas 
    _lineParts = _aLine.Split(new char[] { ' ', '\u000A', ',', '.', ';', ':', '-', '_', '/' }, 
        StringSplitOptions.RemoveEmptyEntries); 
    //keep things going by reading the next  line 
    _aLine = sr.ReadLine(); 
    //words = _lineParts; 
    if (_lineParts != null) 
    { 
        //_words.Add(_lineParts.ToString()); 
        wrd.Add(_lineParts.ToString()); 
    } 
} 

【问题讨论】:

  • 您没有将_lineParts 添加到列表中,而是将_lineParts.ToString() 添加到列表中。 ToString() 对于引用类型的默认行为是输出类型名称,在本例中为 System.String[]。您是否尝试将数组中的每个单独元素添加到列表中?或者您是否尝试将整个数组作为单个元素添加到列表中?
  • 从数组到列表的每个单独元素。

标签: c# arrays list


【解决方案1】:

使用List.AddRange 而不是List.Add

【讨论】:

    【解决方案2】:

    使用List.AddRange 而不是List.Add

    改变

     wrd.Add(_lineParts.ToString());
    

    wrd.AddRange(_lineParts);
    

    【讨论】:

    • 很好 - 我突然想起了我为什么喜欢 javascript :-P
    【解决方案3】:

    您可以在使用List.Add() 的地方使用List.AddRange()

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 2012-09-14
      • 2021-02-23
      • 1970-01-01
      • 2013-08-28
      相关资源
      最近更新 更多