【发布时间】:2021-12-14 09:31:58
【问题描述】:
我有一个简单的字典调用结果:
Dictionary<String,String> results=new();
results["a"]="a";
results["b"]="b";
results["c"]="c";
为了简化示例,我的字典仅包含 3 个字母键 a、b、c。 但有时它不会包含这些值之一,甚至不包含(它总是会被初始化)。 假设这种情况:
Dictionary<String,String> results=new();
if(anyconditionA) results["a"]="a";
if(anyconditionB)results["b"]="b";
if(anyconditionC)results["c"]="c";
所以每次我想使用这本字典进行操作时,我都必须检查键值: 变种测试=结果[“一”]; -> 如果 anycontitionA 不为真,则抛出 System.Collections.Generic.KeyNotFoundException。 所以要解决这个问题:
if(results.ContainsKey("a"){
someOperation(results["a"]);
}
所以如果我有很多值代码如下所示:
if(results.ContainsKey("a"){someOperation(results["a"]);}
if(results.ContainsKey("b"){... stuff}
if(results.ContainsKey("c"){... stuff}
if(results.ContainsKey("..."){... stuff}
if(results.ContainsKey("d"){someOperation(results["d"]);}
¿在一个语句中是否有适当的方法来执行此操作,我的意思是检查并在存在时执行操作,或者我必须在每次该值存在时进行测试? (就像在列表中使用 null 运算符一样 结果[a]?.someOperation() ) 谢谢!
【问题讨论】:
-
查看
TryGetValue和GetValueOrDefault,或者使用 Lookup 代替 -
你应该使用
TryGetValue()
标签: c# .net linq dictionary keynotfoundexception