字典返回默认值,如果该键不存在

编程入门 行业动态 更新时间:2024-10-19 14:28:48
本文介绍了字典返回默认值,如果该键不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我发现自己使用目前的格局常常在我的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 :)

更多推荐

字典返回默认值,如果该键不存在

本文发布于:2023-11-06 14:09:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563908.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   字典   默认值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!