【问题标题】:How to lookup / check a dictionary value by key如何按键查找/检查字典值
【发布时间】:2012-07-29 12:39:26
【问题描述】:

我正在尝试确认特定字典键是否包含值

例如

dict01 在“tester”键中是否包含短语“testing”

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

【问题讨论】:

  • 您可以通过 dict01["tester"] 获取值,然后对值部分执行 .Contains。有什么我想念的吗?如果您知道特定的键,获取它的值,然后简单地搜索该字符串。
  • 这能回答你的问题吗? How to Find Item in Dictionary Collection?

标签: c# .net windows


【解决方案1】:

您可以使用ContainsKeystring.Contains

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

你也可以使用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
}

【讨论】:

  • 这似乎不是一个好方法,因为您没有将两者(键和值)链接在一起,如果我想在键值中搜索特定模式怎么办 - 但是只需一键
  • 使用TryGetValue会更高效。
  • @另外,如何查找实际的键值而不是检查它?
  • @user1559618 检查TryGetValue 示例,它将值加载到dicVal 变量中
  • @des 我以为 jobInformation["ID"].Value 会起作用
【解决方案2】:

如果不想遍历字典两次,可以使用下面的方法

string value;
var result = dict01.TryGetValue("tester", out value) && value.Contains("testing");

【讨论】:

    【解决方案3】:
    if (myDict.ContainsKey("tester"))
        // Do something?
    

    More on MSDN

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      相关资源
      最近更新 更多