如果键不存在,字典返回默认值 [英] Dictionary returning a default value if the key does not exist

查看:40
本文介绍了如果键不存在,字典返回默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己现在在我的代码中经常使用当前模式

I find myself using the current pattern quite often in my code nowadays

var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary

var somethingElse = dictionary.ContainsKey(key) ? dictionary[key] : new List<othertype>();
// Do work with the somethingelse variable

或者有时

var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary

IList<othertype> somethingElse;
if(!dictionary.TryGetValue(key, out somethingElse) {
    somethingElse = new List<othertype>();
}

这两种方式都感觉很迂回.我真正想要的是

Both of these ways feel quite roundabout. What I really would like is something like

dictionary.GetValueOrDefault(key)

现在,我可以为字典类编写一个扩展方法来为我做这件事,但我想我可能会遗漏一些已经存在的东西.SO,有没有一种方法可以在不为字典编写扩展方法的情况下以更容易看"的方式做到这一点?

Now, I could write an extension method for the dictionary class that does this for me, but I figured that I might be missing something that already exists. SO, is there a way to do this in a way that is more "easy on the eyes" without writing an extension method to dictionary?

推荐答案

TryGetValue 已经将类型的默认值分配给字典,因此您可以使用:

TryGetValue will already assign the default value for the type to the dictionary, so you can just use:

dictionary.TryGetValue(key, out value);

并忽略返回值.然而,那真的只返回default(TValue),而不是一些自定义的默认值(也不是,更有用的是,执行委托的结果).框架中没有任何更强大的内置功能.我建议两种扩展方法:

and just ignore the return value. However, that really will just return default(TValue), not some custom default value (nor, more usefully, the result of executing a delegate). There's nothing more powerful built into the framework. I would suggest two extension methods:

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary, 
     TKey key,
     TValue defaultValue)
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary,
     TKey key,
     Func<TValue> defaultValueProvider)
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value
         : defaultValueProvider();
}

(当然,您可能想要进行参数检查:)

(You may want to put argument checking in, of course :)

这篇关于如果键不存在,字典返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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