字典ContainsKey并在一个函数中获取值 [英] Dictionary ContainsKey and get value in one function

查看:221
本文介绍了字典ContainsKey并在一个函数中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以调用一次Dictionary<string, int>来查找键的值?现在我正在打两个电话.

Is there a way to call Dictionary<string, int> once to find a value for a key? Right now I'm doing two calls like.

if(_dictionary.ContainsKey("key") {
 int _value = _dictionary["key"];
}

我想这样做:

object _value = _dictionary["key"] 
//but this one is throwing exception if there is no such key

如果没有这样的键,或者一次调用就可以得到空值,我会希望为空吗?

I would want null if there is no such key or get the value with one call?

推荐答案

您可以使用 TryGetValue

You can use TryGetValue

int value;
bool exists = _dictionary.TryGetValue("key", out value);

TryGetValue如果包含指定的密钥,则返回true,否则返回false.

TryGetValue returns true if it contains the specified key, otherwise, false.

这篇关于字典ContainsKey并在一个函数中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆