用子串搜索Object Book的Dictionary值

时间:2015-12-19 07:52:23

标签: c# dictionary

我有一个带有几个按钮(添加书籍,删除书籍,搜索等)的库GUI,它使用了一个词典。 Book构造函数有2个参数,ISBN和title。我有2个文本框,在添加之前询问用户ISBN和标题。我使用library[ISBNtext.Text] = new Book(ISBNtext.Text, TITLEtext.Text);创建新图书并将其添加到字典中。我需要搜索按钮,通过ISBN或标题使用子字符串搜索字典中的书籍(搜索" cat"将返回"如何照顾你的猫")。 / p>

我的代码如下:

private void searchButton_Click(object sender, EventArgs e)
{
    libraryList.Items.Clear();

    foreach (KeyValuePair<string, Book> book in library)
    {
        if (book.Key.Contains(ISBNtext.Text) || book.Value.Title.Contains(TITLEtext.Text))
        {
            libraryList.Items.Add(String.Format("{0} = {1}", book.Key, book.Value.Title));
        }
    }

    ISBNtext.Clear();
    TITLEtext.Clear();
}

如果我添加一些简单的书籍(ISBN:1 - TITLE:1,ISBN:2 - TITLE:2,ISBN:3 - TITLE:3等)并搜索1它只显示每本书已被添加,而不仅仅是我搜索的那个。

我还应该提到这是针对学校的,所以我不确定我可以使用任何图书馆或任何东西。

3 个答案:

答案 0 :(得分:1)

我认为其他答案可能已经解决了您的代码中的问题,但如果您被要求使用字典,您应该考虑是否应该充分利用它提供的方法。

字典的用途是该键提供了对存储对象的快速查找,与完全搜索列表相比,可以节省时间。

我将您的搜索细分为以下两个单独的搜索作为示例。第一个匹配完整的ISBN号(如果提供)并使用字典的键作为快速查找。第二个是较慢的标题搜索,你可以使用你已经拥有的代码(只需删除它的ISBN部分)。

private void searchButton_Click(object sender, EventArgs e)
{
    libraryList.Items.Clear();

    // ISBN number search
    var isbnNo = ISBNtext.Text;
    if (!string.IsNullOrEmpty(isbnNo)){
      if (library.ContainsKey(isbnNo)){
        var book = library[isbnNo];
        libraryList.Items.Add(String.Format("{0} = {1}", book.ISBNNo, book.Title));
      }
    }

    // Title search
    var titleText = TITLEtext.Text;
    if (!string.IsNullOrEmpty(titleText)){
      foreach (KeyValuePair<string, Book> book in library)
      {
          // search based on title like your existing code
      }
    }

    ISBNtext.Clear();
    TITLEtext.Clear();
}

答案 1 :(得分:0)

您还需要检查ISBNtext.TextTITLEtext.Text是否为空。如果其中任何一个为空contains()将返回true。这就是你得到错误结果的原因。在if子句中添加条件如下: -

if ((book.Key.Contains(ISBNtext.Text) && book.Key != string.Empty) || (book.Value.Title.Contains(TITLEtext.Text) && book.Value.Title != string.Empty) )
        {
            libraryList.Items.Add(String.Format("{0} = {1}", book.Key, book.Value.Title));
        }

答案 2 :(得分:0)

只需添加空输入检查:

foreach (KeyValuePair<string, Book> book in library)
    {
        if (!string.IsNullOrEmpty(ISBNtext.Text) && book.Key.Contains(ISBNtext.Text) || !string.IsNullOrEmpty(TITLEtext.Text) && book.Value.Title.Contains(TITLEtext.Text))
        {
            libraryList.Items.Add(String.Format("{0} = {1}", book.Key, book.Value.Title));
        }
    }