如何找到字典对象中部分匹配的键?

发布于 2024-12-09 12:11:42 字数 199 浏览 1 评论 0原文

我试图根据给定的部分或完全匹配的字符串来获取字典中的所有项目。

我尝试了以下代码,但似乎不起作用

a.Where(d => d.Value.Contains(text)).ToDictionary(d => d.Key, d => d.Value);

您能告诉我如何实现这一目标吗?

I am trying to grab all the items in the dictionary based on given string which matches partially or fully.

I tried the following code but doesn't seems to work

a.Where(d => d.Value.Contains(text)).ToDictionary(d => d.Key, d => d.Value);

Can you please tell me how to achieve this ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

未蓝澄海的烟 2024-12-16 12:11:42

假设您确实想要查找 部分匹配的条目,那么您给出的代码应该绝对可以正常工作。如果你看到其他东西,我怀疑你的诊断有缺陷。如果您想查找 key 部分匹配的条目,您只需交换

a.Where(d => d.Value.Contains(text))

简短

a.Where(d => d.Key.Contains(text))

但完整的程序,演示您给出的代码的工作情况:

using System;
using System.Collections.Generic;
using System.Linq;

class Test
{
    static void Main()
    {
        var original = new Dictionary<string, string> {
            { "a", "foo" },
            { "b", "bar" },
            { "c", "good" },
            { "d", "bad" },
        };

        string needle = "oo";

        var filtered = original.Where(d => d.Value.Contains(needle))
                               .ToDictionary(d => d.Key, d => d.Value);

        foreach (var pair in filtered)
        {
            Console.WriteLine("{0} => {1}", pair.Key, pair.Value);
        }
    }
}

输出:

a => foo
c => good

The code you've given should work absolutely fine, assuming you really wanted to find entries where the value had a partial match. If you're seeing something else, I suspect your diagnostics are flawed. If you wanted to find entries where the key had a partial match, you just want to swap

a.Where(d => d.Value.Contains(text))

for

a.Where(d => d.Key.Contains(text))

Short but complete program demonstrating the code you've given working:

using System;
using System.Collections.Generic;
using System.Linq;

class Test
{
    static void Main()
    {
        var original = new Dictionary<string, string> {
            { "a", "foo" },
            { "b", "bar" },
            { "c", "good" },
            { "d", "bad" },
        };

        string needle = "oo";

        var filtered = original.Where(d => d.Value.Contains(needle))
                               .ToDictionary(d => d.Key, d => d.Value);

        foreach (var pair in filtered)
        {
            Console.WriteLine("{0} => {1}", pair.Key, pair.Value);
        }
    }
}

Output:

a => foo
c => good
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文