是否有一个IDictionary实现的,失踪键,返回抛出的默认值呢? [英] Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?

查看:206
本文介绍了是否有一个IDictionary实现的,失踪键,返回抛出的默认值呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该索引到字典抛出一个异常,如果钥匙丢失。有IDictionary的,与其将返回默认值(T)?

The indexer into Dictionary throws an exception if the key is missing. Is there an implementation of IDictionary that instead will return default(T)?

我知道了TryGetValue的方法,但是这是不可能的使用LINQ使用。

I know about the "TryGetValue" method, but that's impossible to use with linq.

这会有效地做我需要?

myDict.FirstOrDefault(a => a.Key == someKeyKalue);

我不认为它会因为我认为它会重复使用哈希查找的键代替。

I don't think it will as I think it will iterate the keys instead of using a Hash lookup.

推荐答案

事实上,这将不会是有效的。

Indeed, that won't be efficient at all.

您总是可以写一个扩展方法:

You could always write an extension method:

public static TValue GetValueOrDefault<TKey,TValue>
    (this IDictionary<TKey, TValue> dictionary, TKey key)
{
    TValue ret;
    // Ignore return value
    dictionary.TryGetValue(key, out ret);
    return ret;
}

这篇关于是否有一个IDictionary实现的,失踪键,返回抛出的默认值呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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