Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法从';字符串';至';system.collections.generic.list字符串';_C#_String_List_Typeconverter - Fatal编程技术网

C# 无法从';字符串';至';system.collections.generic.list字符串';

C# 无法从';字符串';至';system.collections.generic.list字符串';,c#,string,list,typeconverter,C#,String,List,Typeconverter,我有两张单子 字符串的嵌套列表,以及 字符串列表 在索引列表中,我想用公共值添加行内容,并在两者之间添加单独的字符串:“ 为此,我编写了一段代码,但是,我面临一个问题“无法从‘string’转换为‘system.collections.generic.list string’”。如何解决这个问题 int common = 10; List<List<string>> index = new List<List<string>>(); List<

我有两张单子

  • 字符串的嵌套列表,以及
  • 字符串列表
  • 索引
    列表中,我想用
    公共
    值添加
    行内容
    ,并在两者之间添加单独的字符串
    :“

    为此,我编写了一段代码,但是,我面临一个问题“无法从‘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);
    }
    
    。。。

    您的
    索引
    列表中的每个项目都是一个
    列表
    。当您尝试添加项目时,它应该是一个列表。但是,如果要向其中添加字符串,
    linesOfContent+:“+common
    被视为字符串

    解决方案:

    index[0][0] = 0:10
    index[0][1] = 1:10
    index[0][2] = 2:10
    
    Linq的
    Select
    方法(也称为投影)可用于变换序列中的每个元素:

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

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

    字符串的
    列表的
    列表应包含
    字符串的
    列表,而不是
    int的
    列表

    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);
    }
    
    int公共=10;
    列表索引=新列表();
    列表行内容=新列表();
    对于(int i=0;i<5;i++)
    {
    对于(int j=0;j<5;j++)
    {       
    linesOfContent.Add(i.ToString()+“:“+common.ToString());
    }
    索引。添加(行内容);
    }
    
    这是代码,没有foreach循环,而是使用了
    可枚举。范围

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

    能否在
    索引
    列表中显示预期结果?@shad0wk我希望结果与预期输出一致。