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我希望结果与预期输出一致。