我有一个有几个按钮的库GUI (添加书籍、移除书籍、搜索等)。使用字典。图书构造函数有两个参数,ISBN和title。我有两个文本框,要求用户在添加ISBN和标题之前。我正在使用library[ISBNtext.Text] = new Book(ISBNtext.Text, TITLEtext.Text);创建新书并将它们添加到字典中。我需要搜索按钮来搜索字典中的书籍,无论是ISBN还是使用子字符串的标题(搜索"cat“将返回”如何照顾您的猫“)。
我的代码如下:
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-标题: 1,ISBN: 2-标题: 2,ISBN: 3-标题:3,等等)搜索1,它只显示每一本被添加的书,而不是我搜索的那本。
我也应该提到,这是为了学校,所以我不确定我是否可以使用任何图书馆或任何东西。
发布于 2015-12-19 08:00:51
您还需要检查ISBNtext.Text或TITLEtext.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));
}发布于 2015-12-19 08:24:38
我认为其他答案可能已经解决了代码中的问题,但是如果您被要求使用字典,您应该考虑是否应该充分利用它提供的方法。
字典的目的是,键提供对存储对象的快速查找,这与对列表的完整搜索相比节省了时间。
作为一个例子,我已经把你的搜索分解成两个独立的搜索。第一个匹配完整的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();
}发布于 2015-12-19 08:12:17
只需添加空输入的检查:
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));
}
}https://stackoverflow.com/questions/34368601
复制相似问题