我有一个字典,其中包含 Product
值以及 description
等属性。
在 textbox1_textchanged
处理程序中,我想在字典中搜索在 description
中包含特定文本的产品。
我已经试过了:
var values = (from pv in mydictionary
where pv.Value.description.Contains(textBox1.Text)
select pv.Value);
此代码无效,因为我按下的第二个键值 var 值是空的。
我找到的所有示例都是通过键搜索,但我需要通过字典的值进行搜索。
最佳答案
但是您所拥有的不是有效代码。您正在尝试过滤具有特定描述但缺少关键元素的值。您需要添加 where
子句来完成它。
var values =
from pv in mydictionary
where pv.Value.description.Contains(textBox1.Text)
select pv.Value;
然而,更好的写法是只查看字典的值。
var values =
from value in mydictionary.Values // Note: we're looking through the values only,
// not all the key/value pairs in the dictionary
where value.description.Contains(textBox1.Text)
select value;
要使其不区分大小写,您可以尝试使用 String.IndexOf()
因为这是为数不多的可以忽略大小写进行搜索的比较之一。
var values =
from value in mydictionary.Values
where value.description
.IndexOf(textBox1.Text, StringComparison.OrdinalIgnoreCase) != -1
// any value that isn't `-1` means it contains the text
// (or the description was empty)
select value;
关于c# - 搜索字典的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7407077/