c# - 搜索字典的值

标签 c# linq dictionary

我有一个字典,其中包含 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/

相关文章:

c# - 如何将此列值转换为整数?

c# - 查询嵌套集合(父/子)

linq - 将system.data.linq.binary转换为byte []

javascript - React循环数组和rende对象

javascript - 如何通过映射的 promise 传递数据?

c# - 如何使用两个命名空间查询 XElement

c# - 修复调用K8S API时出现 "The credentials supplied to the package were not recognized"问题

javascript - 挑选一个 JSON 对象来创建多个数组

c# - System.Security.Claims 命名空间的成员不可用?

linq - 是否可以从 DataContext.ExecuteQuery 返回匿名对象的 IEnumerable?