Updating a list within a dictionary

Viewed 92

I'm trying to update a list within a dictionary. I'm not sure whether my approach is the correct way to go about my problem.

I want to map keys against a list and thought I could do this with a dictionary

Dictionary<Occupation, List<Person>> personsWithOccupation = new Dictionary<Occupation, List<Person>>();

OnPersonAdded(Person person){ 
    Occupation occ = person.GetOccupation();
    personsWithOccupation.Add(occ, UPDATE LIST);
}

I understand that I could grab the list out of the dictionary, update it and put it back into the list, but my question, Am I going about this the wrong way?. Should I be mapping these values in a different, more efficient approach?

EDIT:

I'm going to consume these values like this

public List<Person> GetPersonsWithOccupation(Occupation occ){
     return personsWithOccupation[occ];
}
2 Answers

you can add new person to occupation just like this:

OnPersonAdded(Person person) { 
    Occupation occ = person.GetOccupation();
    if (!personWithOccupation.ContainsKey(occ))
        personWithOccupation[acc] = new List<Person>();
    personsWithOccupation[occ].Add(person);
}

I tend to use this code, avoiding double lookups and it's also pretty concise:

(personsWithOccupation.TryGetValue(occ, out var list)  // see if we have the key already
    ? list                  // return list
    : personsWithOccupation[occ] = new List<Person>())  // if not add list and return it
.Add(person);     // add to list
Related