You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio C#中Dictionary的if语句问题及图书搜索优化问询

Hey there! Let's work through your GUI program issues together—getting that partial/ISBN/Title-only search working and squashing those Dictionary if-statement bugs.

Right now, your program only matches full book details, but we can adjust this to let users search by partial ISBN, partial Title, or either field alone. We'll use LINQ to filter the Dictionary's values, since we care about matching the book properties rather than the dictionary keys.

First, let's confirm your Book class setup (adjust if needed):

public class Book
{
    public string Title { get; set; }
    public string ISBN { get; set; }
    public bool OnLoan { get; set; }
}

Assuming your dictionary is defined like this (using ISBN as the key makes sense since it's unique):

private Dictionary<string, Book> bookDictionary = new Dictionary<string, Book>();

Here's a search button click handler that supports partial, case-insensitive matches for both ISBN and Title:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchInput = txtSearchBox.Text.Trim();
    
    if (string.IsNullOrWhiteSpace(searchInput))
    {
        MessageBox.Show("Please enter a search term (ISBN or Title)!");
        return;
    }

    // Filter books where ISBN contains the input, OR Title contains the input
    var matchingBooks = bookDictionary.Values
        .Where(book => 
            book.ISBN.Contains(searchInput, StringComparison.OrdinalIgnoreCase) ||
            book.Title.Contains(searchInput, StringComparison.OrdinalIgnoreCase))
        .ToList();

    if (matchingBooks.Count == 0)
    {
        MessageBox.Show("No matching books found.");
        return;
    }

    // Bind results to your GUI control (e.g., DataGridView, ListBox)
    dgvBookResults.DataSource = matchingBooks;
}

Key Notes:

  • StringComparison.OrdinalIgnoreCase ensures searches work regardless of uppercase/lowercase input.
  • Using Where() on bookDictionary.Values lets us check every book's properties, not just the dictionary keys.
  • This works for partial matches (e.g., typing "123" will find a book with ISBN "978-1234567890") and single-field searches (only ISBN or only Title).

Most Dictionary bugs come from not checking if a key exists before accessing it, or accidentally overwriting entries. Let's cover the most common fixes:

Common Error 1: Accessing a key without checking existence

This throws a KeyNotFoundException if the key doesn't exist:

// ❌ Bad: No check for existing key
string targetISBN = txtISBN.Text.Trim();
Book foundBook = bookDictionary[targetISBN];

Fix: Use TryGetValue (most efficient) or ContainsKey

TryGetValue looks up the key once and returns the book if it exists:

// ✅ Good: Safe key lookup with TryGetValue
string targetISBN = txtISBN.Text.Trim();
if (bookDictionary.TryGetValue(targetISBN, out Book foundBook))
{
    // Update loan status
    foundBook.OnLoan = !foundBook.OnLoan;
    MessageBox.Show($"Updated loan status for: {foundBook.Title}");
}
else
{
    MessageBox.Show("No book found with that ISBN.");
}

Or if you prefer ContainsKey (slightly less efficient, but readable):

// ✅ Good: Check key existence first
if (bookDictionary.ContainsKey(targetISBN))
{
    Book foundBook = bookDictionary[targetISBN];
    foundBook.OnLoan = !foundBook.OnLoan;
    MessageBox.Show($"Updated loan status for: {foundBook.Title}");
}
else
{
    MessageBox.Show("No book found with that ISBN.");
}

Common Error 2: Adding books without checking for duplicate keys

If you add a book with an existing ISBN key, it will overwrite the old entry silently:

// ❌ Bad: No duplicate key check
Book newBook = new Book { Title = txtTitle.Text, ISBN = txtISBN.Text, OnLoan = false };
bookDictionary.Add(newBook.ISBN, newBook);

Fix: Check ContainsKey before adding

// ✅ Good: Prevent duplicate entries
string newISBN = txtISBN.Text.Trim();
string newTitle = txtTitle.Text.Trim();

if (string.IsNullOrWhiteSpace(newISBN) || string.IsNullOrWhiteSpace(newTitle))
{
    MessageBox.Show("Please enter both Title and ISBN!");
    return;
}

if (bookDictionary.ContainsKey(newISBN))
{
    MessageBox.Show("A book with this ISBN already exists!");
    return;
}

Book newBook = new Book 
{ 
    Title = newTitle, 
    ISBN = newISBN, 
    OnLoan = false 
};
bookDictionary.Add(newISBN, newBook);
MessageBox.Show("Book added successfully!");

With these changes, your search will be much more user-friendly, and you'll avoid those frustrating Dictionary-related crashes or unexpected behavior.

内容的提问来源于stack exchange,提问作者John Starwind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:23:31