搜索字典的值

uoa*_*oah 4 c# linq dictionary

我有一个包含Product属性的值的字典description.在textbox1_textchanged处理程序中,我想在字典中搜索具有特定文本的产品description.

我试过这个:

var values = (from pv in mydictionary
              where pv.Value.description.Contains(textBox1.Text)
              select pv.Value);
Run Code Online (Sandbox Code Playgroud)

此代码无效,因为我按下的第二个键值var值为空.

我找到的所有示例都是通过键搜索,但我需要搜索字典的值.

Jef*_*ado 6

但是你拥有的不是有效的代码.您正在尝试过滤具有特定描述但缺少关键元素的值.您需要添加该where子句才能完成它.

var values =
    from pv in mydictionary
    where pv.Value.description.Contains(textBox1.Text)
    select pv.Value;
Run Code Online (Sandbox Code Playgroud)

然而,写这个的更好方法是查看字典的值.

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;
Run Code Online (Sandbox Code Playgroud)

为了使它不区分大小写,您可以尝试使用,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;
Run Code Online (Sandbox Code Playgroud)