3

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?

1
  • 3
    second foreach is unnecessary, just use resultarray[b] = list.ToArray(); Commented Oct 24, 2013 at 13:01

2 Answers 2

10

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" },
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I've been trying to wrap my head around LINQ but I still don't quite understand it. I'll do some more reading.
@reallybadatmath basically what it says is "create a projection, where each item becomes the result of ToArray() on that item; and then create an array from the results of that projection"
Thankyou again Marc. Your explanation makes sense -- a LOT simpler than trying to target the indexes with incrementing integers.
3

Before the inner loop:

resultarray[b] = new string[list.Count];

1 Comment

If we were going to anything with the inner loop, @sasjaq has the truth of it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.