我有以下两个变量:
List<List<string>> result
string[][] resultarray
我想从结果中获取值并读取它们并将它们存储在 resultarray 中,如下所示: [[“一”、“二”]、[“三”]、[“四”、“五”、“六”]、[“七”]、[“八”]]等
我有以下代码:
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;
但是,在调试时,我在尝试递增 a 或 b 时收到“NullExceptionError:未设置对象实例的对象引用”。我也试过将它们声明为:
int a = 0
int b = 0
...这也行不通。我没有正确声明这些,还是与 foreach 循环有关?
最佳答案
每个子数组都以 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" },
};
关于c# - List<List<string>> 值到 string[][] 数组 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19566579/