我創建了一個專案,該專案從 CSV 檔案中讀取,該檔案包含班級學生的姓名和分數。該程式應該從 CSV 檔案中讀取,然后輸出所有名稱。我已經創建了該程式并且它可以作業,只是我只能輸出班級中 1 名學生的姓名和分數,當它是 12 時。如果有人可以告訴我我需要在哪里更改代碼以便獲得整個班級的輸出,將不勝感激。謝謝。
public static void Main(string[] args)
{
string[] names = loadNames();
int[] marks = loadMarks();
outputMarks(names, marks);
Console.ReadKey();
}
static string[] loadNames()
{
string filename = @"testMarks.csv";
string[] tempData;
string[] tempNames = new string[2];
using (StreamReader currentfile = new StreamReader(filename))
{
tempData = currentfile.ReadLine().Split(',');
}
tempNames[0] = tempData[0];
tempNames[1] = tempData[1];
return tempNames;
}
static int[] loadMarks()
{
string filename = @"testMarks.csv";
string[] tempData;
using (StreamReader currentfile = new StreamReader(filename))
{
tempData = currentfile.ReadLine().Split(',');
}
int[] tempMarks = new int[tempData.Length - 2];
for (int i = 2; i < tempData.Length; i )
{
tempMarks[i - 2] = int.Parse(tempData[i]);
}
return tempMarks;
}
static void outputMarks(string[] names, int[] marks)
{
for (int i = 0; i < 2; i )
{
Console.Write(names[i] "\t");
}
for (int i = 0; i < 6; i )
{
Console.Write(marks[i] "\t");
}
Console.WriteLine();
}
}
}
uj5u.com熱心網友回復:
假設 testMarks.csv 的內容是這樣的(當然沒有空行):
約翰、亞當斯、100、79、77、83、55、37
莎拉、巴克斯特、99、66、78、57、62、70
簡、克拉格、100、100、61、95、59、38
我會這樣做:
public static void Main(string[] args)
{
var allStudentsAndNotes = LoadStudentsAndNotes();
Console.ReadKey();
}
private List<Student> LoadStudentsAndNotes()
{
string pth = @"C:\MyDesktopPath\testMarks.csv";
var lines = System.IO.File.ReadAllLines(pth);
var studentList = new List<Student>();
Student student;
foreach (var line in lines)
{
student = new Student();
var datas = line.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
student.FirstName = datas[0];
student.LastName = datas[1];
for (int i = 2; i < datas.Length; i )
{
student.Notes.Add(int.Parse(datas[i]));
}
studentList.Add(student);
}
return studentList;
}
一個小班
class Student
{
public Student()
{
Notes = new List<int>();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public List<int> Notes { get; set; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/372790.html
