Reading from a sequential file into an array of structs
I have the following struct:
public struct StudentDetails
{
public string unitCode; //eg CSC10208
开发者_开发知识库 public string unitNumber; //unique identifier
public string firstName; //first name
public string lastName;// last or family name
public int studentMark; //student mark
}
Using that struct I wrote data into a sequential file. The data in the file is as follow:
ABC123
1
John
Doe
95
DCE433
3
Sherlock
Holmes
100
ASD768
5
Chuck
Norris
101
etc.
What's the best way to read the data from that file and load it into an array of structs?
Assuming your file is one value per line:
List<StudentDetails> studentList = new List<StudentDetails>();
using (StreamReader sr = new StreamReader(@"filename"))
{
while (!sr.EndOfStream)
{
StudentDetails student;
student.unitCode = sr.ReadLine();
student.unitNumber = sr.ReadLine();
student.firstName = sr.ReadLine();
student.lastName = sr.ReadLine();
student.studentMark = Convert.ToInt32(sr.ReadLine());
studentList.Add(student);
}
StudentDetail[] studentArray = studentList.ToArray();
}
Note that this is not very robust - if there are not 5 lines for each student, you'll run into problems, or if the last student has less than 5 lines.
EDIT
Taking the lessons learned from your previous question Array of structs in C# regarding the need to override ToString()
in your struct
, the following might help to resolve your issue with printing the values:
In StudentDetails struct (taken from Nick Bradley's answer):
public override string ToString()
{
return string.Format("{0}, {1}, {2}, {3}, {4}", unitCode,
unitNumber, firstName, lastName, studentMark);
}
Then you could simply loop through the array:
for (int i = 0; i < studentArray.Length; i++)
{
Console.WriteLine("Student #{0}:", i);
Console.WriteLine(studentArray[i]);
Console.WriteLine();
}
Initially I'de use some sort of Serialization to write to the file since it will also take care of the reading part as well.
But given the way you created the file, I'de use StreamReader and it's ReadLine() method - since you know what the order of the properties you wrote to the server a simple while:
string line = "";
while ((line = reader.ReadLine()) != null)
{
YourStruct t = new YourStruct();
t.unitCode = line;
t.unitNumber = reader.ReadLine();
...
resultArray.Add(t);
}
reader.Close(); reader.Dispose();
精彩评论