【问题标题】:Cannot convert from 'string' to 'system.collections.generic.list string'无法从“字符串”转换为“system.collections.generic.list 字符串”
【发布时间】:2016-08-11 04:46:56
【问题描述】:

我有两个列表

  1. 字符串的嵌套列表,并且
  2. 字符串列表

index 列表中,我想添加带有common 值的linesOfContent,在两者之间我想添加单独的字符串":"

为此,我编写了一个代码,但是,我遇到了一个问题“无法从 'string' 转换为 'system.collections.generic.list string'”。如何解决这个问题。

int common = 10;
List<List<string>> index = new List<List<string>>();
List<int> linesOfContent = new List<int>();
for(int i = 0; i < 5; i++)
{
      for(int j = 0; j < 5; j++)
      {       
             linesOfContent.Add(i+":"+common);
      }
      index.Add(linesOfContent);
}

预期输出:

index[0][0] = 0:10
index[0][1] = 1:10
index[0][2] = 2:10

... ...

【问题讨论】:

  • 你能在index List 中显示预期的结果吗?
  • @shad0wk 我想要一个符合预期输出的结果。

标签: c# string list typeconverter


【解决方案1】:

字符串中的ListLists 应包含string 中的Lists,而不是int 中的Lists

int common = 10;
List<List<string>> index = new List<List<string>>();
List<string> linesOfContent = new List<string>();
for(int i = 0; i < 5; i++)
{
    for(int j = 0; j < 5; j++)
    {       
        linesOfContent.Add(i.ToString() +":"+common.ToString());
    }
    index.Add(linesOfContent);
}

【讨论】:

    【解决方案2】:

    index 列表中的每一项都是List&lt;string&gt;。当您尝试添加一个项目时,它应该是一个列表。但是,您尝试向其添加字符串,linesOfContent+":"+common 被视为字符串。

    解决方案:

    Linq 的Select 方法(又名投影)可用于转换序列中的每个元素:

    index.Add(linesOfContent.Select(x=> x.ToString()  + ":" + common).ToList());
    

    请注意,您构建循环的方式会导致一些重复记录。

    【讨论】:

      【解决方案3】:

      这是代码,没有 foreach 循环,而是使用Enumerable.Range

      linesOfContent.AddRange(Enumerable.Range(0, 5).Select(i => i.ToString() + ":" + common.ToString()).ToArray());
      index.Add(linesOfContent);
      

      【讨论】:

        猜你喜欢
        • 2017-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多