Dictionary with multiple values per key in C#

By FoxLearn 1/22/2025 6:29:08 AM   311
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.

How to initialize dictionary in C#?

In C#, you can initialize a dictionary in several ways, but the most common method is by using the Dictionary<TKey, TValue> constructor.

C# inline dictionary initialization is simple. To initialize a dictionary without values, you can write it like this.

// initialize an empty dictionary
var studentScores = new Dictionary<string, int>();
// or
Dictionary<string, int> studentScores = new Dictionary<string, int>();

The proper way to initialize a c# dictionary, then set values later.

// Add values to the dictionary
studentScores["Alice"] = 85;
studentScores["Bob"] = 90;
studentScores["Charlie"] = 88;

Using Add Method

You can create an empty dictionary where the key is a string and the value is an int, then add key-value pairs later.

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("cherry", 3);

Using Collection Initializer

You can initialize a dictionary with key-value pairs using a collection initializer.

// c# initialize dictionary with values
Dictionary<string, int> dict = new Dictionary<string, int>
{
    { "apple", 1 },
    { "banana", 2 },
    { "cherry", 3 }
};

Using LINQ

You can also initialize a dictionary using LINQ if you have a collection of keys and values that you want to map into a dictionary.

// c# initialize dictionary from list.
var myList = new List<Tuple<string, int>> 
{
    new Tuple<string, int>("apple", 1),
    new Tuple<string, int>("banana", 2),
    new Tuple<string, int>("cherry", 3)
};

Dictionary<string, int> dict = myList.ToDictionary(t => t.Item1, t => t.Item2);

Using ToDictionary for Collections

If you have an array or collection and you want to create a dictionary, you can use ToDictionary.

var items = new[] { "apple", "banana", "cherry" };
Dictionary<string, int> dict = items.Select((item, index) => new { item, index }).ToDictionary(x => x.item, x => x.index);

In C# 6.0 and later, you can create a dictionary like this:

var dict = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};

This syntax also works with custom types.

Dictionary with multiple values per key C#

Creating a dictionary of lists, where each key points to a list of integers:

// Declare dictionary of lists - dictionary multiple values per key c#
var dictionary = new Dictionary<string, List<int>>();

// Add keys with multiple values
// c# dictionary 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.

// 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.

// 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.

C# Multi key Dictionary

If you need to use multiple keys for each entry, you can create a composite key using a tuple.

For example, a dictionary with multiple keys in C# can use a Tuple as a composite key.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary where the key is a tuple of two integers
        var multiKeyDict = new Dictionary<(int, int), string>();

        // Add items with composite keys (tuples)
        multiKeyDict[(1, 2)] = "First";
        multiKeyDict[(2, 3)] = "Second";
        multiKeyDict[(1, 3)] = "Third";

        // Access an item by its composite key
        Console.WriteLine(multiKeyDict[(1, 2)]);  // Output: First
        Console.WriteLine(multiKeyDict[(2, 3)]);  // Output: Second
    }
}

C# Dictionary 3 values

If you need to store three values for each key, you can either use a tuple, a custom class, or a structure to store those three values.

For example, using a Dictionary with a Tuple that holds three values:

// c# initialize dictionary with multiple values
Dictionary<string, Tuple<int, string, bool>> myDictionary = new Dictionary<string, Tuple<int, string, bool>>();

// Adding some entries
myDictionary["key1"] = new Tuple<int, string, bool>(1, "value1", true);
myDictionary["key2"] = new Tuple<int, string, bool>(2, "value2", false);

// Accessing the values
var value = myDictionary["key1"];
Console.WriteLine($"Key1: {value.Item1}, {value.Item2}, {value.Item3}");

You can use a custom class to store multiple values for each key.

For example, using a custom class that holds three values:

// c# multi dictionary
public class MyValue
{
    public int Value1 { get; set; }
    public string Value2 { get; set; }
    public bool Value3 { get; set; }
}

Dictionary<string, MyValue> myDictionary = new Dictionary<string, MyValue>();

// Adding some entries
myDictionary["key1"] = new MyValue { Value1 = 1, Value2 = "value1", Value3 = true };
myDictionary["key2"] = new MyValue { Value1 = 2, Value2 = "value2", Value3 = false };

// Accessing the values
var value = myDictionary["key1"];
Console.WriteLine($"Key1: {value.Value1}, {value.Value2}, {value.Value3}");

Both methods allow you to associate three values with each key in the dictionary.