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