List> 值转换为 string[][] 数组 C#
本文关键字:List string 数组 转换 | 更新日期: 2023-09-27 18:36:53
我有以下两个变量:
List<List<string>> result
string[][] 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" },
};
在内部循环之前:
resultarray[b] = new string[list.Count];