繁体   English   中英

字典在同一项目中包含键和值

[英]Dictionary ContainsKey & Value in same Item

我需要检查我的字典是否在同一行上包含两个值。 例如:

Dictionary<string, string> ServiceLIST = new Dictionary<string, string>();
ServiceLIST.add(ServiceName,ServiceStatus)
//if (ServiceLIST.ContainsKey("testingName") & (ServiceLIST.ContainsKey("testingStatus"))

如何替换if语句来检查字典中同一项目上是否同时存在“ testingName”和&“ testingStatus”?

怎么样:

if(ServiceLIST.ContainsKey("testingName") 
 && ServiceLIST["testingName"] == "testingStatus")

paqogomez的解决方案有效,但是它需要您两次遍历字典-一次检查值是否在字典中,另一次查找它所映射的内容。 通常,这不是什么大问题,但是如果字典很大,或者您需要多次执行此操作,则很浪费。

MaMazav的解决方案也不错,但是如前所述,它的可读性较差,并且需要使用KeyValuePairs(我个人不喜欢)。

我认为最好的解决方案是:

string mappedValue;
if(ServiceLIST.TryGetValue("testingName", out mappedValue) && mappedValue == "testingValue")
{
    ...
}

保持可读性和性能。

这是MaMazav提供的小提琴: http ://dotnetfiddle.net/2UG0QH

另外,不确定这是否是实际的代码示例,但您可能应该使用C#编码约定进行变量命名:)

if (ServiceLIST.Contains(new KeyValuePair<string, string>(
    "testingName", "testingStatus")))

您可以使用LINQ

if(ServiceLIST.Any(x => x.Key == "testingName" && x.Value == "testingStatus"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM