Key-Value Pairs in C#
Understanding key-value pairs is a foundational skill for any C# developer. While dictionaries are the most common implementation, they require keys to be unique. In many real-world scenarios, however, you may need to store multiple values for the same key — and that’s where alternative structures like lists of key-value pairs or dictionaries with list values come in. This guide explores flexible key-value strategies in C#, along with operations such as adding, selecting, grouping, and sorting.
What is a Key-Value Pair?
A key-value pair associates a key (identifier) with a value (data). It’s used to organize and retrieve data efficiently. But when you need duplicate keys or groupings, a standard dictionary may fall short.
Use Cases:
- Logging events with duplicate timestamps
- Grouping tags, categories, or comments under the same heading
- Collecting form field inputs where the same field may appear more than once
Representing Duplicate Keys in C#
1. Using List<KeyValuePair<TKey, TValue>>
Allows multiple entries with the same key:
var entries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Category", "Tech"),
new KeyValuePair<string, string>("Category", "Science"),
new KeyValuePair<string, string>("Category", "AI")
};
2. Dictionary with List Values
You can also group values under the same key:
var grouped = new Dictionary<string, List<string>>
{
{ "Category", new List<string> { "Tech", "Science", "AI" } }
};
See here for more details on C# Dictionaries
Operations on List-Based Key-Value Pairs
✅ Adding Entries
entries.Add(new KeyValuePair<string, string>("Tag", "C#"));
Finding All Values for a Key
var allTags = entries.Where(e => e.Key == "Tag")
.Select(e => e.Value)
.ToList();
Grouping by Key
var groupedTags = entries.GroupBy(e => e.Key)
.ToDictionary(g => g.Key, g => g.Select(e => e.Value).ToList());
Sorting by Key
var sorted = entries.OrderBy(e => e.Key).ToList();
Sorting by Value
var sortedByValue = entries.OrderBy(e => e.Value).ToList();
Converting Between Structures
From List to Dictionary (Allowing Grouped Values)
var dict = entries.GroupBy(e => e.Key)
.ToDictionary(g => g.Key, g => g.Select(e => e.Value).ToList());
From Dictionary with List Values to Flat List
var flatList = grouped.SelectMany(kvp =>
kvp.Value.Select(val => new KeyValuePair<string, string>(kvp.Key, val))
).ToList();
JSON Serialization with Duplicates
When serializing multiple values under one key:
using System.Text.Json; // goes at top of file
string json = JsonSerializer.Serialize(grouped);
Deserialization:
var deserialized = JsonSerializer.Deserialize<Dictionary<string, List<string>>>(json);
Real-World Examples
Logging Multiple Events Per Type
var logs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Error", "File not found"),
new KeyValuePair<string, string>("Error", "Null reference"),
new KeyValuePair<string, string>("Info", "Started service")
};
HTTP Query Parameters (Multiple Same Keys)
var queryParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("filter", "active"),
new KeyValuePair<string, string>("filter", "admin")
};
Summary
- Use
List<KeyValuePair<TKey, TValue>>
for duplicate keys - Use
Dictionary<TKey, List<TValue>>
to group multiple values under one key - LINQ enables filtering, grouping, sorting, and transformations
- Easily serialize grouped data structures to and from JSON
Understanding how to use flexible key-value structures in C# makes your code more adaptable and scalable — especially when working with unstructured, grouped, or repeated data.