Cannot convert from 'string' to 'system.collections.generic.list string'
Solution 1
A List
of Lists
of string should contain Lists
of string
, not Lists
of 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);
}
Solution 2
Each item in your index
list is a List<string>
. When you try to add an item, it should be a List. However, you're trying to add a string to it, linesOfContent+":"+common
is considered a string.
Solution:
Linq's Select
Method (aka Projection) can be used to transform each element inside a sequence:
index.Add(linesOfContent.Select(x=> x.ToString() + ":" + common).ToList());
Be aware that the way you're constructing your loops results in some duplicate records.
Related videos on Youtube
Siva S
Updated on June 04, 2022Comments
-
Siva S almost 2 years
I have the two list
- nested list of string, and
- list in string
In
index
list, I want to addlinesOfContent
with acommon
value and in-between i want to add separate string":"
.For that i write a code, but, I face a problem "cannot convert from 'string' to 'system.collections.generic.list string'". How to solve this.
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); }
Expected Output:
index[0][0] = 0:10 index[0][1] = 1:10 index[0][2] = 2:10
... ...
-
Zein Makki almost 8 yearsCan you show the expected results inside
index
List ? -
Siva S almost 8 years@shad0wk I want a result as in expected output.