c# - List<List<string>> 值到 string[][] 数组 C#

标签 c# string list multidimensional-array

我有以下两个变量:

        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/

相关文章:

c# - 剧作家 "Element is not attached to the DOM"

python - 是否有Python 'shortcut' 来定义一个类变量等于它自己名字的字符串版本?

java - 从数据库到应用范围

c# - 有关如何教程(WPF/Entity Framework/ObservableCollections)的问题

c# - 在 ASP.NET Core 中引用现有的 .NET Framework 项目

java - 选择组合框中的任何项目时,向文本字段写入内容

python - 与 python 中每个确切位置的列表进行比较

R 给定相同维度数据表的列表,生成每个单元格均值的汇总

c# - 使用 Linq 识别编码声明

c# - 在文件加载时重新格式化文件中的日期