I have the a following two variables:
List<List<string>> result
string[][] resultarray
I want to take the values from result and read store them in resultarray like so: [["one", "two"], ["three"], ["four", "five", six"], ["seven"], ["eight"]] etc.
I have the following code:
string[][] resultarray = new string[resultint][];
int a = new int();
int b = new int();
foreach (List<string> list in result)
{
foreach (string s in list)
{
resultarray[b][a] = s;
a++;
}
b++;
}
return resultarray;
However, when debugging, I get a "NullExceptionError: Object reference not set to an instance of an object" when trying to increment a or b. I've also tried declaring them as:
int a = 0
int b = 0
...This doesn't work either. Am I not declaring these correctly or does it have to do with the foreach loop?
Each sub-array starts as null - you need to create the inner arrays.
But a simpler approach is:
var resultarray = result.Select(x => x.ToArray()).ToArray();
which gives the stated outcome if we assume the input is something like:
var result = new List<List<string>> {
new List<string> { "one", "two" },
new List<string> { "three" },
new List<string> { "four", "five", "six" },
new List<string> { "seven" },
new List<string> { "eight" },
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With