0

What is the C# equivalent of doing:

>>> from collections import defaultdict
>>> dct = defaultdict(list)
>>> dct['key1'].append('value1')
>>> dct['key1'].append('value2')
>>> dct
defaultdict(<type 'list'>, {'key1': ['value1', 'value2']})

For now, I have:

Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
dct.Add("key1", "value1");
dct.Add("key1", "value2");

but that gives errors like "The best overloaded method match has invalid arguments".

BioGeek
  • 21,897
  • 23
  • 83
  • 145

3 Answers3

2

Here's an extension method you can add to your project to emulate the behavior you want:

public static class Extensions
{
    public static void AddOrUpdate<TKey, TValue>(this Dictionary<TKey, List<TValue>> dictionary, TKey key, TValue value)
    {
        if (dictionary.ContainsKey(key))
        {
            dictionary[key].Add(value);
        }
        else
        {
            dictionary.Add(key, new List<TValue>{value});
        }
    }
}

Usage:

Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
dct.AddOrUpdate("key1", "value1");
dct.AddOrUpdate("key1", "value2");
Sven Grosen
  • 5,616
  • 3
  • 30
  • 52
1

Your first step should be creating the record with specified key. Then you can add additional values to the value list:

Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
dct.Add("key1", new List<string>{"value1"});
dct["key1"].Add("value2");
Andrei
  • 55,890
  • 9
  • 87
  • 108
  • Any way to get the default values the Python version provides? This seems to require different code depending on whether or not a key is already present. – user2357112 Jan 28 '14 at 15:42
  • @user2357112, out of the box - no. You can always implement extension for that though – Andrei Jan 28 '14 at 15:45
0
Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
List<string>() mList = new List<string>();
mList.Add("value1");
mList.Add("value2");

dct.Add("key1", mList);
Sameer
  • 2,143
  • 1
  • 16
  • 22