简体   繁体   English

默认字典,带有C#中的列表

[英]Default dictionary with lists in C#

Is there a way to have a Dictionary in C# that will automatically have an empty list associated with any key, other than creating such a class myself? 除了我自己创建这样的类之外,还有什么方法可以使C#中的Dictionary自动具有与任何键关联的空列表? I would like to avoid the following code if possible: 如果可能,我想避免使用以下代码:

int x = 0;
int y = 42;
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();

List<int> newList;
if (dict.containsKey(x))
{
    dict[x].Add(y);
}
else
{
    dict[x] = new List<int>{y};
}

or possibly: 或可能:

int x = 0;
int y = 42;
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();

List<int> newList;
if (dict.TryGetValue(x, out newList))
{
    newList.Add(y);
}
else
{
    dict[x] = new List<int>{y};
}

This behavior can be abstracted nicely with an extension method. 使用扩展方法可以很好地抽象此行为。

public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> valueFactory)
{
    if (dictionary == null) throw new ArgumentNullException(nameof(dictionary));
    if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory));

    TValue value;
    if (!dictionary.TryGetValue(key, out value))
    {
        value = valueFactory.Invoke(key);
        dictionary.Add(key, value);
    }
    return value;
}

The method signature is identical to ConcurrentDictionary.GetOrAdd() . 方法签名与ConcurrentDictionary.GetOrAdd()相同。

var list = dict.GetOrAdd(x, (_) => new List<int>());
list.Add(y);

you already have answer, dictionary does not have such ability, using extension method just fakes it and hides the fact that you are looking up dictionary twice (in case key doesn't exist). 您已经有了答案,字典没有这种能力,使用扩展方法只是伪造它,并且隐藏了您两次查找字典的事实(以防键不存在)。 but you will write one line of code if that makes you happy. 但是如果您感到满意,您将编写一行代码。

In c#7 how ever you can pack things more a little bit. 在c#7中,您可以多打包一些东西。

if (dict.TryGetValue(x, out var list)) list.Add(y);
else dict.Add(x, new List<int>{y});

this will have one lookup if key already exist, and two lookups if key doesn't exist. 如果密钥已经存在,则将进行一次查找,如果密钥不存在,则将进行两次查找。

Usually my code is: 通常我的代码是:

if (!dict.containsKey(x)) 
    dict[x] = new List<int>();

dict[x].Add(y);

I believe it's easier to read 我相信它更容易阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM