Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<List<string>> values to into string[][] array C#

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?

like image 558
reallybadatmath Avatar asked Dec 29 '25 16:12

reallybadatmath


1 Answers

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" },
};
like image 51
Marc Gravell Avatar answered Dec 31 '25 05:12

Marc Gravell