CutHimSomeSlack
CutHimSomeSlack

Reputation: 193

Adding to Values of a Dictionary

With simpler dictionaries like this Dictionary<key,value> I know I can add an item to the dictionary like this:

if(!myDic.ContainKeys(key))
  myDic[key] = value;

But how about a more complex dictionary like this:

Dictionary myDic<string, List<MyClass>>

where each key might have a list of values of my class? How do we add to that?

Upvotes: 1

Views: 106

Answers (4)

MJVC
MJVC

Reputation: 507

If the value to add is an item for the list, you can do:

if(!myDic.Keys.Contains(key)) {
    myDic[key] = new List<MyClass>();
}
myDic[key].Add(value);

Upvotes: 2

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You can use TryGetValue method:

List<MyClass> list;

if (myDic.TryGetValue(key, out list))
  list.Add(value); // <- Add value into existing list
else
  myDic.Add(key, new List<MyClass>() {value}); // <- Add new list with one value

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726469

Here is a code snippet that I use for this:

// This is the list to which you would ultimately add your value
List<MyClass> theList;
// Check if the list is already there
if (!myDict.TryGetValue(key, out theList)) {
    // No, the list is not there. Create a new list...
    theList = new List<MyCLass>();
    // ...and add it to the dictionary
    myDict.Add(key, theList);
}
// theList is not null regardless of the path we take.
// Add the value to the list.
theList.Add(newValue);

This is the most "economical" approach, because it does not perform multiple searches on the dictionary.

Upvotes: 5

Matt Burland
Matt Burland

Reputation: 45135

The same way:

myDic[key] = new List<MyClass()>();

If the list is already there and you want to add to it:

myDic[key].Add(new MyClass());

Upvotes: 5

Related Questions