[英]C# read from a file and save into arraylist
我有一個學生文本文件,我必須閱讀並將其保存在數組列表中。 文件的正式形式是拳頭名稱,名字,標記,每個名稱都用新行寫成,請幫我解決該問題。文件格式:
First Name
Last Name
Marks
First Name
Last Name
Marks
First Name
Last Name
Marks
到目前為止,這是我嘗試過的方法:
List<string> fileContent = new List<string>();
TextReader tr = new StreamReader("A.txt");
string currentLine = string.Empty;
while ((currentLine = tr.ReadLine()) != null)
{
fileContent.Add(currentLine);
}
下面是讀取指定格式的文件並將結果推送到People的List(如果需要,則為ArrayList)的示例。 基於此,您可以根據自己的喜好創建一個字符串列表,盡管我懷疑您想要一個人列表?
class Program
{
static void Main(string[] args)
{
string fn = @"c:\myfile.txt";
IList list = new ArrayList();
FileReader(fn, ref list);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i].ToString());
}
Console.ReadKey();
}
public static void FileReader(string filename, ref IList result)
{
using (StreamReader sr = new StreamReader(filename))
{
string firstName;
string lastName;
string marks;
IgnoreHeaderRows(sr);
while (!sr.EndOfStream)
{
firstName = sr.EndOfStream ? string.Empty : sr.ReadLine();
lastName = sr.EndOfStream ? string.Empty : sr.ReadLine();
marks = sr.EndOfStream ? string.Empty : sr.ReadLine();
result.Add(new Person(firstName, lastName, marks));
}
}
}
const int HeaderRows = 2;
public void IgnoreHeaderRows(StreamReader sr)
{
for(int i = 0; i<HeaderRows; i++)
{
if(!sr.EndOfStream) sr.ReadLine();
}
}
}
public class Person
{
string firstName;
string lastName;
int marks;
public Person(string firstName, string lastName, string marks)
{
this.firstName = firstName;
this.lastName = lastName;
if (!int.TryParse(marks, out this.marks))
{
throw new InvalidCastException(string.Format("Value '{0}' provided for marks is not convertible to type int.", marks));
}
}
public override string ToString()
{
return string.Format("{0} {1}: {2}", this.firstName, this.lastName, this.marks);
}
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
}
JohnLBevan-要在FileReader中調用IgnoreHeaderRows,我們需要將IgnoreHeaderRows更改為static,因為無法通過靜態方法訪問非靜態成員。 如果我錯了糾正我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.