我有一个txt文件,其中包含有关不同图书的信息(名称,出版商,作者,年份等),并且我需要该程序打印出仅由某些出版商出版的图书名称(在我的情况下为“ O” Reilly”)。
我尝试使用File.ReadAllLines或name.Contains(“ O'Reilly”),但是总是出现错误。抱歉,如果我做一些愚蠢的事情,只是从C#开始
static void Task1()
{
List<Book> namings = Book.GetBooks("books.txt");
var resul = from name in namings
where name.Contains("O'Reilly")
select name;
namings.ToList().ForEach(x => x == "O'Reilly" Console.WriteLine($" '{x.Name}' by {x.Publisher}"));
}
public class Book
{
public string Name;
public string Publisher;
public string Author;
public int Year;
public int Edition;
public string ISBN;
public string List => $"Name: {Name}\nPublisher: {Publisher}\nAuthor: {Author}\nYear: {Year}\nEdition: {Edition}\nISBN: {ISBN}\n";
public static List<Book> GetBooks(string filename)
{
List<Book> result = new List<Book>();
string[] lines = File.ReadAllLines(filename);
foreach (string line in lines)
{
try
{
string[] fields = line.Split(';');
Book b = new Book()
{
Name = fields[0],
Publisher = fields[1],
ISBN = fields[2],
Author = fields[3],
Edition = int.Parse(fields[4]),
Year = int.Parse(fields[5]),
};
result.Add(b);
}
catch (Exception e)
{
Console.WriteLine($"An exception occured while reading the following line:{line}\nException:{e.Message}");
}
}
return result;
}
public static void WriteBooks(string filename, List<Book> books)
{
List<string> lines = new List<string>();
foreach (Book book in books)
{
lines.Add($"{book.Name};{book.Publisher};{book.ISBN};{book.Author};{book.Year};{book.Edition}");
}
File.WriteAllLines(filename, lines);
}
}
这是txt文件:
C ++编程语言; Addison-Wesley; 978-0321563842; Bjarne Stroustrup; 4; 2013
简而言之Java; O'Reilly; 978-1449370824; Benjamin J.Evans和David Flanagan; 6; 2015年
C#深度;曼宁; 978-1617294532;乔恩·斯基特; 4; 2018年
设计Web API; O'Reilly; 978-1492026921; Brenda Jin,Saurabh Sahni和Amir Shevat; 1; 2018年
我希望程序会打印出来:
出版商O'Reilly: 简而言之Java 设计Web API;
答案 0 :(得分:0)
知道了。
List<Book> names = Book.GetBooks("books.txt");
Console.WriteLine("Books that are published by O'Reilly:");
var a = names.Where(x => x.Publisher.Contains("O'Reilly"));
a.ToList().ForEach(x => Console.WriteLine("---> '" + x.Name + "'"));