C# 如何按键查找/检查字典值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11709294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to lookup / check a dictionary value by key
提问by user1559618
I am trying to confirm whether a specific dictionary key contains a value
我正在尝试确认特定字典键是否包含值
e.g.
例如
does dict01 contain the phrase "testing" in the "tester" key
dict01 是否在“tester”键中包含短语“testing”
At the moment I am having to iterate through the dictionary using KeyPair, which I don't want to have to do as it wasting performance
目前我不得不使用 KeyPair 遍历字典,我不想这样做,因为它会浪费性能
采纳答案by Zbigniew
You can use ContainsKeyand string.Contains:
您可以使用ContainsKey和string.Contains:
var key = "tester";
var val = "testing";
if(myDictionary.ContainsKey(key) && myDictionary[key].Contains(val))
{
// "tester" key exists and contains "testing" value
}
You can also use TryGetValue:
您还可以使用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
}
回答by Shai
回答by M. Mennan Kara
You can use the following method if you don't want to iterate through the dictionary twice
如果不想遍历字典两次,可以使用以下方法
string value;
var result = dict01.TryGetValue("tester", out value) && value.Contains("testing");

