如何在Dictionary <string,List <string [] >>()对象中检查字符串值?

kmk*_*09k 5 c# dictionary

为了简单起见,我有以下字典,我为每个字符串键填充了未知数量的字符串.我还有以下字符串列表.

var dict = new Dictionary<string, List<string[]>>();
IList<string> headerList = new List<string>();
Run Code Online (Sandbox Code Playgroud)

如何检查列表中的字符串是否是字典中的值?我的数据看起来与此类似:

 Key           Value
 -----         ------------------
 Car           honda, volks, benz
 Truck         chevy, ford
Run Code Online (Sandbox Code Playgroud)

我需要检查"honda"是否包含在字典值中.我想我需要做类似以下的事情来查看值是否包含列表,其中包含有问题的字符串.请记住,我对C#还不熟悉.

    foreach (string header in headerList)
    {
        // This is wrong, I don't know what to put in the if statement 
        if (dict.ContainsValue(r => r.Contains(header)))
        {
            // do stuff 
        }
    }
Run Code Online (Sandbox Code Playgroud)

Mic*_*han 4

约翰·奥多姆是对的,你需要一个列表。

我建议您HashSet<string>在内部使用 a 来获取 的值Diictionary。例如Dictionary<string, HashSet<string>>

然后当需要查询时,你可以这样做:

 headerList.Where(x => dict.Values.Any(d => d.Contains(x))).ToList()
Run Code Online (Sandbox Code Playgroud)

查看.NET 嵌套循环与哈希查找的性能比较