从顺序文件读入结构数组
我有以下结构:
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
}
使用该结构我将数据写入顺序文件。文件中的数据如下:
ABC123
1
John
Doe
95
DCE433
3
Sherlock
Holmes
100
ASD768
5
Chuck
Norris
101
等。
从该文件读取数据并将其加载到结构数组中的最佳方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您的文件每行一个值:
请注意,这不是很稳健 - 如果每个学生没有 5 行,或者如果最后一个学生的行数少于 5 行,您就会遇到问题。
编辑
从上一个问题中吸取教训C# 中的结构数组< /a> 关于需要重写
struct
中的ToString()
,以下内容可能有助于解决打印值的问题:在 StudentDetails 结构中(取自 Nick Bradley 的回答):
然后你可以简单地循环数组:
Assuming your file is one value per line:
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 yourstruct
, the following might help to resolve your issue with printing the values:In StudentDetails struct (taken from Nick Bradley's answer):
Then you could simply loop through the array:
最初,我使用某种 序列化 来写入文件,因为它还会处理阅读部分。
但考虑到您创建文件的方式,我使用 StreamReader< /a> 它是 ReadLine() 方法 - 因为您很快就知道写入服务器的属性的顺序:
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: