Menu
CoddyTech

用 LINQ 搜索

本课属于 Coddy C# 学习旅程的“面向对象编程”单元。第 65 课,共 70 课。

challenge icon

挑战

简单

使用 LINQ 为你的图书馆系统添加强大的搜索功能!你将实现一些方法,让用户按不同条件查找图书,包括按书名搜索、按作者筛选和查找可借阅的图书。LINQ 能让这些查询简洁易读。

你将继续使用现有的项目结构:

  • Book.cs:保留你的 Book 类,其中包含 Id、Title、Author 和 IsAvailable 属性,以及 Borrow() 和 Return() 方法。
  • User.cs:保留你的 User 类及其借阅跟踪功能,包括 MaxBooks、CanBorrow() 和用于管理已借阅图书的方法。
  • Library.cs:你将在这里添加由 LINQ 支持的搜索方法。除了现有的借阅逻辑,还要实现以下搜索功能:
    • SearchByTitle(string keyword):返回书名中包含关键词的所有图书(不区分大小写)
    • GetBooksByAuthor(string author):返回指定作者的所有图书(完全匹配,不区分大小写)
    • GetAvailableBooks():返回当前所有可借阅的图书
    • GetBorrowedBooks():返回当前所有已借出的图书
    每个搜索方法都应返回一个可迭代的图书集合。
  • Program.cs:处理搜索查询并显示结果。

你将收到以下输入:

  • 图书馆名称
  • 图书数量,接着是每本图书的信息,格式为 id|title|author
  • 用于设置初始状态的借阅操作数量,接着是每次操作的 bookId
  • 以下格式之一的搜索命令:
    • title|keyword:按书名关键词搜索图书
    • author|name:按作者查找图书
    • available:获取所有可借阅的图书
    • borrowed:获取所有已借出的图书

对于搜索结果,请按照 {Title} by {Author} 的格式,每行打印一本匹配的图书。如果没有匹配的图书,请打印 No books found。结果应按图书在图书馆集合中的顺序打印。

例如,输入如下:

City Library
5
B001|The Hobbit|Tolkien
B002|The Lord of the Rings|Tolkien
B003|1984|George Orwell
B004|Animal Farm|George Orwell
B005|The Silmarillion|Tolkien
2
B001
B003
author|Tolkien

输出应为:

The Hobbit by Tolkien
The Lord of the Rings by Tolkien
The Silmarillion by Tolkien

下面是另一个示例,使用相同的图书馆设置,但搜索可借阅的图书:

City Library
5
B001|The Hobbit|Tolkien
B002|The Lord of the Rings|Tolkien
B003|1984|George Orwell
B004|Animal Farm|George Orwell
B005|The Silmarillion|Tolkien
2
B001
B003
available

输出应为:

The Lord of the Rings by Tolkien
Animal Farm by George Orwell
The Silmarillion by Tolkien

LINQ 可以将原本复杂的循环转换为清晰易读的查询。使用 Where() 进行筛选、使用 ToList() 生成结果列表等方法,能让你的搜索实现简洁且易于维护!

亲手试试

using System;
using System.Collections.Generic;

namespace LibrarySystem
{
    class Program
    {
        public static void Main(string[] args)
        {
            // 读取图书馆名称
            string libraryName = Console.ReadLine();
            
            // 用图书馆名称创建一个 Library 实例
            Library library = new Library(libraryName);
            
            // 读取图书数量
            int numBooks = Convert.ToInt32(Console.ReadLine());
            
            // 读取并添加图书
            for (int i = 0; i < numBooks; i++)
            {
                string bookInput = Console.ReadLine();
                string[] bookParts = bookInput.Split('|');
                string bookId = bookParts[0];
                string bookTitle = bookParts[1];
                string bookAuthor = bookParts[2];
                
                Book book = new Book(bookId, bookTitle, bookAuthor);
                library.AddBook(book);
            }
            
            // 读取借阅操作的数量,用于设置初始状态
            int numBorrows = Convert.ToInt32(Console.ReadLine());
            
            // 处理借阅操作(只读取图书 ID)
            for (int i = 0; i < numBorrows; i++)
            {
                string bookId = Console.ReadLine();
                Book book = library.GetBookById(bookId);
                if (book != null)
                {
                    book.IsAvailable = false;
                }
            }
            
            // 读取搜索命令
            string searchCommand = Console.ReadLine();
            
            // 处理搜索命令
            List<Book> results = new List<Book>();
            
            if (searchCommand == "available")
            {
                results = library.GetAvailableBooks();
            }
            else if (searchCommand == "borrowed")
            {
                results = library.GetBorrowedBooks();
            }
            else if (searchCommand.Contains("|"))
            {
                string[] parts = searchCommand.Split('|');
                string searchType = parts[0];
                string searchValue = parts[1];
                
                if (searchType == "title")
                {
                    results = library.SearchByTitle(searchValue);
                }
                else if (searchType == "author")
                {
                    results = library.GetBooksByAuthor(searchValue);
                }
            }
            
            // 输出结果
            if (results.Count == 0)
            {
                Console.WriteLine("No books found");
            }
            else
            {
                foreach (Book book in results)
                {
                    Console.WriteLine($"{book.Title} by {book.Author}");
                }
            }
        }
    }
}

面向对象编程中的所有课

自己练习: C# 在线编译器