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?

4

2 に答える 2

10

各サブ配列は次のように始まります-内部配列を作成nullする必要があります。

しかし、より簡単なアプローチは次のとおりです。

var resultarray = result.Select(x => x.ToArray()).ToArray();

入力が次のようなものであると仮定すると、次の結果が得られます。

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" },
};
于 2013-10-24T12:59:43.657 に答える
3

内側のループの前:

resultarray[b] = new string[list.Count];
于 2013-10-24T13:00:57.383 に答える