0

I have a Dictionary>. Is there any function which gets the list at a particular key, and or creates a list if it does not exist. For example, this does not work:

Dictionary<string, List<string>> d = new Dictionary<string, List<string>>();
d["Bob"].Add("Fred");

Right now I'd have to do this:

Dictionary<string, List<string>> d = new Dictionary<string, List<string>>();
List<string> l = d["Bob"];
if(l == null) { l = d["Bob"] = new List<string>(); }
l.Add("Fred");

I've considered adding an extension method Get(T key), which would allow me to do this:

Dictionary<string, List<string>> d = new Dictionary<string, List<string>>();
d.Get("Bob").Add("Fred");

But I wanted to check to see if something like this doesn't already exist.

Looks like this is a dupe, that had a good answer:

.NET Dictionary: get or create new

Community
  • 1
  • 1
bpeikes
  • 3,495
  • 9
  • 42
  • 80
  • That would throw an exception if the "Bob" key is not present. Instead you'd want to use `TryGetValue`. – juharr Aug 23 '16 at 18:25
  • 2
    @neverendingqs No, the OP wants to also add something when missing, not just return the default. – juharr Aug 23 '16 at 18:27

1 Answers1

0

You can create an extension method like:

public static void CreateNewOrUpdateExisting<TKey, TValue>(
    this IDictionary<TKey, TValue> map, TKey key, TValue value)
{
    map[key] = value;
}

Source: Method to Add new or update existing item in Dictionary

Community
  • 1
  • 1
Vivek Sharma
  • 1,912
  • 1
  • 13
  • 15
  • 2
    The OP isn't trying to do an update or insert, which you've show is already built in, but a get or insert. – juharr Aug 23 '16 at 18:30