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

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

问题描述

我发现自己使用目前的格局常常在我的code时下

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)

现在,我可以写字典的类,它这对我来说一个扩展方法,但我想,我可能会丢失已经存在的东西。那么,有没有一种方式,一种方式是更容易对眼睛,而无需编写扩展方法来字典做到这一点?

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);

和忽略返回值。然而,真正的将会的只是返回默认(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天全站免登陆