1
我想從文本文件填充列表。從文本文件填充列表<T>
public class Book
{
public string Title { get; set; }
public string Year { get; set; }
}
該文本文件的標題和年份在一行接一行。
List<Book> BookList = new List<Book>();
//assume the path is correct
string[] lines = File.ReadAllLines(path);
如何填充該數組中的列表,而不會覆蓋Book對象,通過這兩個領域都填充給定記錄之前,每一次。
foreach (string line in lines)
{
int n;
Book record = new Book();
if (!int.TryParse(line, out n))
{
record.Title = line;
}
else
{
record.PublicationYear = line;
BookList.Add(record);
}
}
標題:年份:1955 標題年份:1947年 的標題缺失。 – user1327418
文本文件的格式是什麼? – Meccano
該文本文件在一行上有一個標題,下一個在其出版年。所以每個List記錄有兩行。 – user1327418