如何按键查找/检查字典值

use*_*618 8 .net c# windows

我试图确认特定的字典键是否包含值

例如

dict01在"tester"键中包含短语"testing"

目前我不得不使用KeyPair迭代字典,我不想这样做因为它浪费性能

Zbi*_*iew 15

您可以使用ContainsKeystring.Contains:

var key = "tester";
var val = "testing";
if(myDictionary.ContainsKey(key) && myDictionary[key].Contains(val)) 
{
    // "tester" key exists and contains "testing" value
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用TryGetValue:

var key = "tester";
var val = "testing";
var dicVal = string.Empty;
if(myDictionary.TryGetValue(key, out dicVal) && dicVal.contains(val)) 
{
    // "tester" key exists and contains "testing" value
}
Run Code Online (Sandbox Code Playgroud)