.NET词典:获取或创建新的 [英] .NET Dictionary: get or create new
问题描述
我经常发现自己创造了 词典
与非平凡值类(如 列表
),然后一直在填充数据写入时相同的code模式。
I often find myself creating a Dictionary
with a non-trivial value class (e.g. List
), and then always writing the same code pattern when filling in data.
例如:
var dict = new Dictionary<string, List<string>>();
string key = "foo";
string aValueForKey = "bar";
这就是我要插入栏
出的对应键富
的名单,其中key 富
可能不被映射到任何东西。
That is, I want to insert "bar"
into the list that corresponds to key "foo"
, where key "foo"
might not be mapped to anything.
这是我用不断重复的图案:
This is where I use the ever-repeating pattern:
List<string> keyValues;
if (!dict.TryGetValue(key, out keyValues))
dict.Add(key, keyValues = new List<string>());
keyValues.Add(aValueForKey);
是否有这样做的更优雅的方式?
Is there a more elegant way of doing this?
相关问题没有回答这个问题:
Related questions that don't have answers to this question:
- Is there an IDictionary implementation that returns null on missing key instead of throwing?
- Find-or-insert with only one lookup in c# dictionary
- Dictionary returning a default value if the key does not exist
推荐答案
我们有一个稍微不同的看法这一点,但效果是相似的:
We have a slightly different take on this, but the effect is similar:
public static TValue GetOrCreate<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
where TValue : new()
{
TValue val;
if (!dict.TryGetValue(key, out val))
{
val = new TValue();
dict.Add(key, val);
}
return val;
}
调用:
var dictionary = new Dictionary<string, List<int>>();
List<int> numbers = dictionary.GetOrCreate("key");
它使用通用约束的公共参数构造函数:其中TValue:新的()
要帮助发现,除非扩展方法是相当具体到一个狭窄的问题,我们往往把扩展方法在它们被扩展类型的命名空间,在这种情况下:
To help with discovery, unless the extension method is quite specific to a narrow problem, we tend to place extension methods in the namespace of the type they are extending, in this case:
namespace System.Collections.Generic
在大多数情况下,使用类型的人具有用一个顶级
语句,因此智能感知也会找到扩展方法为它在你的$ C定义$ C。
Most of the time, the person using the type has the using
statement defined at the top, so IntelliSense would also find the extension methods for it defined in your code.
这篇关于.NET词典:获取或创建新的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!