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

Gra*_*per 0 .net c# linq generics dictionary

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

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

a.Where(d => d.Value.Contains(text)).ToDictionary(d => d.Key, d => d.Value);
Run Code Online (Sandbox Code Playgroud)

你能告诉我如何实现这个目标吗?

Jon*_*eet 7

你给的代码应该工作精绝,假设你真的想找到,其中有部分匹配.如果你看到别的东西,我怀疑你的诊断有缺陷.如果你想找到密钥部分匹配的条目,你只想交换

a.Where(d => d.Value.Contains(text))
Run Code Online (Sandbox Code Playgroud)

对于

a.Where(d => d.Key.Contains(text))
Run Code Online (Sandbox Code Playgroud)

简短而完整的程序演示了您工作的代码:

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

输出:

a => foo
c => good
Run Code Online (Sandbox Code Playgroud)