c# - 用文件 C# 填充锯齿状数组

标签 c# file jagged-arrays

我似乎无法弄清楚如何使用 Jagged Arrays 和 Files。我有三个文件,其中包含数字,我想将每个文件读入其自己的数组。这是我到目前为止所拥有的。试图填充 [0] 数组但无济于事。任何帮助表示赞赏。也找不到任何有关执行此操作的教程。

private void button1_Click(object sender, EventArgs e)
{
    StreamWriter section1;
    StreamWriter section2;
    StreamWriter section3;
    StreamReader section1read;
    StreamReader section2read;
    StreamReader section3read;

    section1 = File.CreateText("Section1.txt");
    section2 = File.CreateText("Section2.txt");
    section3 = File.CreateText("Section3.txt");

    int[][] Scores = new int[3][];

    Random randnum = new Random();

    for (int i = 0; i < 12; ++i)
    {
        int num = randnum.Next(55, 99);
        section1.WriteLine(num);
    }

    for (int j = 0; j < 8; ++j)
    {
        int num1 = randnum.Next(55, 99);
        section2.WriteLine(num1);
    }

    for (int k = 0; k < 10; ++k)
    {
        int num3 = randnum.Next(55, 99);
        section3.WriteLine(num3);
    }

    section1.Close();
    section2.Close();
    section3.Close();

    section1read = File.OpenText("Section1.txt");

    int nums = 0;
    while (!section1read.EndOfStream)
    {
        Scores[0][nums] = int.Parse(section1read.ReadLine());
        ++nums;
    }
    for (int i = 0; i < Scores.Length; ++i)
    {
        listBox1.Items.Add(Scores[0][i]);
    }
    section1read.Close();
}

最佳答案

锯齿状数组应该分两步初始化:

  1. 数组本身:

    int[][] Scores = new int[3][];
    
  2. 子数组:

    Scores[0] = new int[12];
    Scores[1] = new int[8];
    Scores[2] = new int[10];
    

数组是一种固定长度的数据结构。如果事先不知道大小,则必须使用动态长度结构。最好的选择是 List<> 类:

List<List<int>> scores = new List<List<int>>();

scores.Add( new List<int>() );

using( StreamReader section1read = File.OpenText("Section1.txt"))
{
    string line;
    while ((line = section1read.ReadLine()) != null)
    {
        scores[0].Add(int.Parse(line));
    }
}

这里还有其他需要考虑的事情:

关于c# - 用文件 C# 填充锯齿状数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15583452/

相关文章:

file - 在Scheme R6RS中是否可以有效地从磁盘加载整个文件?

c# - Npgsql/PostgreSQL : "function does not exist" error message when it does

c# - 将 List<T> 转换为 HashTable

c# - 如何检查文件是否存在c#

Python 多重处理和目录创建

c# - 将不同类型的数组存储到锯齿状数组中

arrays - 交错数组作为 vba sub 的参数

c# - 锯齿状数组类型属性

c# - 如何将以下 c(++)-struct 转换为 C# 以供 p/invoke 使用

c# - SpecFlow 错误 : One or more step definitions are not implemented yet