读取文件并将值存储到2D数组中

时间:2015-06-24 10:25:35

标签: c# .net arrays 2d

我有一个包含以下内容的文件:

S5555; 100 70 70 100
S3333; 50 50 50 50
S2222; 20 50 40 70
S1111; 90 80 90 85
S4444; 70 80 90 50

当用户点击按钮1时,它应该将文件存储学生ID存入studentIDArr(例如S5555),其他值存入4x5数组marksMatrix,每个值占据数组中的一个位置。

我是否正确地将值存储到studentIDArr中?至于marksMatrix,我试图粗略地编码我认为它的工作方式,但我也不完全确定(有些评论)。我只能使用数组。

string[,] marksMatrix = new string[4,5];
string[] studentIDArr = new string[5];

private void button1_Click(object sender, EventArgs e)
{
    textBox2.Clear();

    try
    {
        using (StreamReader sr = new StreamReader("C:/Users/Y400/dDesktop/CTPrac/CTPrac/input.txt"))
        {
            string x = null;
            while ((x = sr.ReadLine()) != null)
            {
                for (int j = 0; j < studentIDArr.Length; j++)
                {
                    studentIDArr[j] = x;
                }
            }
        }

        textBox2.Text = "File Loading done.\r\n";
        textBox2.Text += "Number of records read: " + studentIDArr.Length;
    }
    catch (IOException ex)
    {
        textBox2.Text = "The file could not be read. " + ex.Message;
    }

    string a, b, c;
    for (int i = 0; i < studentIDArr.Length; i++)
    {
        //a = (String)studentIDArr[i];

        //    string[] abc = Regex.Split(a, ";");
        //    b = abc[0];
        //    c = abc[1];
        //    bc =; 

        for (int y = 0; y < 6; y++)
        {
            for (int x = 0; x < 5; x++)
            {
                //marksMatrix[y, x] = z;
            }
        }
    }

    button1.Enabled = false;
}

1 个答案:

答案 0 :(得分:0)

你只需使用for循环即可。

string[,] marksMatrix = new string[4, 5];
string[] studentIDArr = new string[5];

var lines = File.ReadAllLines("C:/Users/Y400/dDesktop/CTPrac/CTPrac/input.txt");
for (int i = 0; i < lines.Length; i++)
{
    var parts = lines[i].Split(new[] {';', ' ' });
    studentIDArr[i] = parts[0];
    for (int j = 1; j < parts.Length; j++)
    {
        marksMatrix[j - 1, i] = parts[j];
    }
}

这种编码方式是如此难以理解,尝试定义一个类来存储学生ID和标记。

 public class Student
 {
     public string Id { get; set; }
     public List<string> Marks { get; set; }

     public Student()
     {
         this.Marks = new List<string>();
     }
 }

然后代码看起来像这样

var students = new List<Student>();
foreach (var line in File.ReadLines("C:/Users/Y400/dDesktop/CTPrac/CTPrac/input.txt"))
{
    var parts = line.Split(new[]{';', ' '}).ToList();
    students.Add(new Student()
    {
        Id = parts[0],
        Marks = parts.GetRange(1, 4)
    });
}