Dictionary with multiple values per key in C#

By FoxLearn 2/11/2025 4:43:52 AM   947
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;

C# Initialize dictionary with multiple values

In C#, you can initialize a dictionary with multiple values by either using collection initialization syntax or adding key-value pairs after the dictionary is created.

Here are a few ways to initialize a dictionary with multiple values:

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.

// dictionary with multiple keys c#
// Create a dictionary where the key is a tuple of two integers
var multiKeyDict = new Dictionary<(int, int), string>();

// c# dictionary composite key
// Add items with composite keys (tuples)
// c# dictionary with 2 keys
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; }
}

// c# dictionary multiple values per key
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.

Dictionary with Two Keys in C#

In C#, a Dictionary can only have a single key for each entry. However, if you want to store multiple keys for each value, you can use a composite key or tuple as the dictionary's key.

One way to achieve this is by using a Tuple (or a custom class/struct) as the dictionary key, which will allow you to have multiple keys for each entry.

For example, using Tuple as a key

// Dictionary with two keys C#
// Create a dictionary where the key is a Tuple of two strings
Dictionary<Tuple<string, string>, int> personAge = new Dictionary<Tuple<string, string>, int>();

// Add items to the dictionary
personAge.Add(Tuple.Create("John", "Smith"), 30);
personAge.Add(Tuple.Create("Jane", "Doe"), 25);
personAge.Add(Tuple.Create("Mark", "Johnson"), 40);
personAge.Add(Tuple.Create("Mary", "Brown"), 35);

// Retrieve and display values using two keys (first and last name)
foreach (var entry in personAge)
{
     var keys = entry.Key;
     Console.WriteLine("First Name: {0}, Last Name: {1}, Age: {2}", keys.Item1, keys.Item2, entry.Value);
}

Output:

First Name: John, Last Name: Smith, Age: 30
First Name: Jane, Last Name: Doe, Age: 25
First Name: Mark, Last Name: Johnson, Age: 40
First Name: Mary, Last Name: Brown, Age: 35

In this example:

  • The Dictionary<Tuple<string, string>, int> uses a Tuple<string, string> as the key, which means you are using two strings (first name and last name) as the key.
  • Tuple.Create("John", "Smith") creates the composite key for each dictionary entry.
  • You can then retrieve the values by referring to the two parts of the key (Item1 and Item2 of the tuple).

If you want more control over the keys, you can create a custom class or struct to represent the composite key.

For example, Using a custom Class/Struct

using System;
using System.Collections.Generic;

class Program
{
    public class NameKey
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public NameKey(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }

        // Override Equals and GetHashCode for proper key comparison
        public override bool Equals(object obj)
        {
            var other = obj as NameKey;
            return other != null && other.FirstName == this.FirstName && other.LastName == this.LastName;
        }

        public override int GetHashCode()
        {
            return (FirstName, LastName).GetHashCode();
        }
    }

    static void Main()
    {
        // Create a dictionary using a custom class as the key
        Dictionary<NameKey, int> personAge = new Dictionary<NameKey, int>();

        // Add items to the dictionary
        personAge.Add(new NameKey("John", "Smith"), 30);
        personAge.Add(new NameKey("Jane", "Doe"), 25);
        personAge.Add(new NameKey("Mark", "Johnson"), 40);
        personAge.Add(new NameKey("Mary", "Brown"), 35);

        // Retrieve and display values using the custom key
        foreach (var entry in personAge)
        {
            var keys = entry.Key;
            Console.WriteLine("First Name: {0}, Last Name: {1}, Age: {2}", keys.FirstName, keys.LastName, entry.Value);
        }
    }
}

This custom NameKey class can be used to create a dictionary with composite keys and allows you to define additional logic for equality comparison and hashing.