C# – Dictionary with multiple values per key

Each dictionary key maps to exactly one value. When you want multiple values per key, you can use a dictionary of lists. Here’s an example of creating a dictionary of lists, where each key maps to multiple ints:

using System.Collections.Generic;

//Declare dictionary of lists
var dictionary = new Dictionary<string, List<int>>();

//Add keys with multiple values
dictionary.Add("Bob", new List<int>() { 2, 4 });
dictionary.Add("Teddy", new List<int>() { 1, 3 });
Code language: C# (cs)

Notice that you can add to the dictionary like normal. The difference with a dictionary of lists is when you add a key, you need to add a new list (with or without initial values).

Using a dictionary of lists is good when you have a dynamic number of values per key. When you have a fixed number of values and they’re related (such as a person’s age, birthdate, etc…), use a dictionary of tuples (or create a class with the properties you need).

Add values to the key’s list

Usually you’ll have to add additional values to the key’s list. To do this, use Dictionary.TryGetValue() to get the list if the key exists. If it doesn’t exist, add the key with a new list. Then add items to the list. Here’s an example:

using System.Collections.Generic;

//Create dictionary
var dictionary = new Dictionary<string, List<int>>();

//Get existing list or initialize key/list
if (!dictionary.TryGetValue("Bob", out List<int> list))
{
    list = new List<int>();
    dictionary.Add("Bob", list);
}

//Add to list
list.Add(1);
list.Add(2);

Console.WriteLine($"Bob's list has: {string.Join(",", list)}");
Code language: C# (cs)

This outputs the following (showing that it added items to the key’s list):

Bob's list has: 1,2Code language: plaintext (plaintext)

Remove value from the key’s list

To remove a value from the key’s list, use Dictionary.TryGetValue() to get the list if the key exists. Then remove the item from the list. Here’s an example:

using System.Collections.Generic;

//Create dictionary
var dictionary = new Dictionary<string, List<int>>();
dictionary.Add("Bob", new List<int>() { 1, 2, 3 });

//Conditionally remove value from key's list
if (dictionary.TryGetValue("Bob", out List<int> list))
{
    list.Remove(1);
}

Console.WriteLine($"Bob's list has: {string.Join(",", list)}");
Code language: C# (cs)

This outputs the following (showing that it removed the 1 from the list):

Bob's list has: 2,3Code language: plaintext (plaintext)

Leave a Comment