从多个文本文件初始化2d数组c#

时间:2016-03-31 23:51:08

标签: c# arrays multidimensional-array

我目前正在构建一个c#控制台应用程序,用于显示,搜索和排序超过80年的天气数据。为此,我正在实施一个二维数组,以包含年,月,太阳,雨,空气霜和最大值的数据。最低温度(存储在.txt文件中),如下所示:

string[,] Ws1Data = new string[lineCount,7]{
            File.ReadAllLines(@"CMP1124M_Weather_Data\Year.txt"),
            File.ReadAllLines(@"CMP1124M_Weather_Data\Month.txt"),
            File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_Sun.txt"),
            File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_Rain.txt"),
            File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_AF.txt"),
            File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_TMin.txt"),
            File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_TMax.txt"),
        };

但是,当我编译代码时,我得到以下错误:

program.cs(66,35): error CS0150: A constant value is expected
program.cs(67,5): error CS0846: A nested array initializer is expected

有人可以解释这些错误以及如何有效地实现这个二维数组,谢谢。

2 个答案:

答案 0 :(得分:0)

您只能使用常量初始化二维数组,如下所示:

string[,] Ws1Data = new string[2, 7]
{
    { "3", "7", "7", "7", "7", "7", "7" },
    { "3", "7", "7", "7", "7", "7", "7" },
};

我认为在你的情况下你最好使用锯齿状数组。这样做:

string[][] Ws1Data = new []
{
    File.ReadAllLines(@"CMP1124M_Weather_Data\Year.txt"),
    File.ReadAllLines(@"CMP1124M_Weather_Data\Month.txt"),
    File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_Sun.txt"),
    File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_Rain.txt"),
    File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_AF.txt"),
    File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_TMin.txt"),
    File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_TMax.txt"),
};

答案 1 :(得分:-1)

我认为必须修复多维数组的第一维。 尝试这样的事情:

    string[][] Ws1Data = new string[8][];

    Ws1Data[0] = File.ReadAllLines(@"CMP1124M_Weather_Data\Year.txt");

    Ws1Data[1] = File.ReadAllLines(@"CMP1124M_Weather_Data\Year.txt");

    Ws1Data[2] = File.ReadAllLines(@"CMP1124M_Weather_Data\Month.txt");

    Ws1Data[3] = File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_Sun.txt");

    Ws1Data[4] = File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_Rain.txt");

    Ws1Data[5] = File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_AF.txt");

    Ws1Data[6] = File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_TMin.txt");

    Ws1Data[7] = File.ReadAllLines(@"CMP1124M_Weather_Data\WS1_TMax.txt");