Dictionary with multiple values per key in C#

By FoxLearn 12/20/2024 8:43:27 AM   26
Each dictionary key in C# maps to exactly one value. However, if you need to store multiple values for a single key, you can use a dictionary of lists.

Here's an example that demonstrates creating a dictionary of lists, where each key points to a list of integers:

using System.Collections.Generic;

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

// Add keys with multiple values
dictionary.Add("Alice", new List<int>() { 5, 8 });
dictionary.Add("John", new List<int>() { 3, 7 });

In this example, the dictionary associates each key with a list of integers.

When you add a key to the dictionary, you need to provide a new list (either empty or initialized with values).

A dictionary of lists is helpful when you expect each key to have a varying number of values. On the other hand, if the values are fixed and related (e.g., someone's name, age, and birthdate), you might prefer using a dictionary of tuples or defining a custom class for better structure.

Adding Values to the List for a Key

In many cases, you'll need to add additional values to the list associated with a key. This can be done by first checking if the key already exists in the dictionary, using Dictionary.TryGetValue() to retrieve the list. If the key doesn’t exist, you create a new list and add it to the dictionary.

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("Alice", out List<int> list))
{
    list = new List<int>();
    dictionary.Add("Alice", list);
}

// Add to list
list.Add(10);
list.Add(12);

Console.WriteLine($"Alice's list has: {string.Join(",", list)}");

This code outputs:

Alice's list has: 10,12

In this example, we check if "Alice" already has a list of values in the dictionary. If not, we create a new list and add it. Then, we add new values to Alice’s list.

Removing Values from a Key’s List

To remove a value from the list associated with a key, you again use Dictionary.TryGetValue() to retrieve the list. Once you have the list, you can remove the desired value.

Here’s an example:

using System.Collections.Generic;

// Create dictionary
var dictionary = new Dictionary<string, List<int>>();
dictionary.Add("Alice", new List<int>() { 5, 8, 10 });

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

Console.WriteLine($"Alice's list has: {string.Join(",", list)}");

This will output:

Alice's list has: 5,10

In this case, we removed the number 8 from Alice's list. The key remains in the dictionary, but the list now only contains 5 and 10.