A thread-safe, high-performance multi-map for .NET — a dictionary that holds more than one value per key.
var map = new MultiMap<string, int>();
map.Add("primes", 2);
map.Add("primes", 3);
map.Add("primes", 5);
map["primes"]; // [2, 3, 5]
map.Count; // 1 (keys)
map.ValueCount; // 3 (pairs).NET already has a multi-map: ILookup<TKey, TValue>, which you get from Enumerable.ToLookup. But it is immutable — once built, you cannot add or remove anything. So everyone ends up hand-rolling Dictionary<TKey, List<TValue>> and re-writing the same "does the list exist yet?" boilerplate.
MultiMap<TKey, TValue> is the mutable counterpart, and it implements ILookup<TKey, TValue> — so it drops straight into code that already expects a lookup.
ILookup<string, Order> lookup = map; // no conversion, no copydotnet add package MultiMap.NET
Targets netstandard2.0 — works on .NET Framework 4.6.1+, .NET Core 2.0+, and every modern .NET.
- Multiple values per key with
Add,AddRange,Remove,RemoveAll. - Thread-safe. Backed by
ReaderWriterLockSlim, so concurrent readers never block each other. Every returned collection is a snapshot, so you can enumerate while other threads mutate. - Implements
ILookup<TKey, TValue>for drop-in LINQ interop. - Insertion order preserved under each key, in both duplicate modes.
- Optional duplicate rejection — list semantics by default, set semantics on request.
- Custom comparers for keys and values.
- No dependencies.
using MultiMaps;
// Duplicate values allowed under a key (default)
var map = new MultiMap<string, int>();
// Reject a value already present under that key
var unique = new MultiMap<string, int>(allowDuplicateValues: false);
// Custom comparers
var caseInsensitive = new MultiMap<string, int>(
allowDuplicateValues: true,
keyComparer: StringComparer.OrdinalIgnoreCase,
valueComparer: null);
// From existing pairs
var copied = new MultiMap<string, int>(existingPairs);map.Add("a", 1); // true
map.AddRange("a", new[] { 2, 3 }); // 2 (how many were added)
unique.Add("a", 1); // true
unique.Add("a", 1); // false — already theremap["a"]; // [1, 2, 3]
map["missing"]; // [] — empty, never throws
map.TryGetValues("a", out var values); // true, values = [1, 2, 3]
map.ContainsKey("a"); // true
map.ContainsPair("a", 2); // true — this exact pair
map.ContainsValue(2); // true — under any keymap[key] returns an empty sequence for an unknown key rather than throwing — it follows ILookup, not Dictionary.
Two different numbers, so they get two different names:
map.Count; // number of KEYS (this is what ILookup.Count means)
map.ValueCount; // number of PAIRSmap.Remove("a", 2); // true — removes ONE occurrence of that value
map.RemoveAll("a"); // 2 — removes the key and returns how many values went with it
map.Clear();A key disappears automatically once its last value is removed.
MultiMap is an ILookup, so it enumerates as one IGrouping per key:
foreach (var group in map)
{
Console.WriteLine($"{group.Key}: {string.Join(", ", group)}");
}
var all = map.SelectMany(g => g).ToList();Build one straight from a sequence, the same way you would call ToLookup:
var byFirstLetter = words.ToMultiMap(w => w[0]);
var lengthsByLetter = words.ToMultiMap(w => w[0], w => w.Length);
byFirstLetter.Add('z', "zebra"); // ...but unlike ToLookup, you can still change itmap.Pairs(); // IEnumerable<KeyValuePair<TKey, TValue>>, one entry per pair
map.ToDictionary(); // Dictionary<TKey, List<TValue>>, an independent copy
map.Keys; // snapshot of keys
map.Values; // snapshot of every valueIf you know this data structure by the name Microsoft used in the unreleased Microsoft.Experimental.Collections package, that name works too:
var dictionary = new MultiValueDictionary<string, int>();MultiValueDictionary<TKey, TValue> derives from MultiMap<TKey, TValue> and behaves identically. Use whichever reads better.
Reads take a shared lock, writes take an exclusive one. Each individual operation is atomic.
Every collection handed back — map[key], Keys, Values, Pairs(), ToDictionary(), and enumeration — is a snapshot taken under the lock. That means iterating a MultiMap while another thread mutates it will never throw InvalidOperationException, unlike iterating a Dictionary.
Note that a sequence of operations is not atomic as a group. This is a race, and no collection can fix it for you:
if (!map.ContainsPair("a", 1)) // another thread can add it right here
map.Add("a", 1);Use allowDuplicateValues: false and let Add return false instead.
- Lookup, add and remove-by-key are O(1) on the key.
Remove(key, value)scans that one key's values to find the occurrence: O(n) in the size of that key's bucket.- With
allowDuplicateValues: false, eachAddscans that key's bucket for a match: O(n) in the size of that bucket. This is the price of keeping insertion order; for the handful of values a typical key holds it is faster than a hash set, but it is worth knowing if you plan to put thousands of values under a single key. ContainsValuescans everything: O(n) in total pairs.
What does a thread-safe, snapshot-returning multi-map cost compared with the
Dictionary<TKey, List<TValue>> everyone writes by hand? Three implementations, 1,000 int keys with
1 or 10 int values each:
Dictionary<K, List<V>>: no synchronization, and reads hand out the live list. The baseline.Dictionary<K, List<V>>+lock: one exclusive lock, and reads copy the bucket, so it gives the same guarantees asMultiMap.MultiMap:ReaderWriterLockSlim, reads copy the bucket.
Each cell is the mean time for the whole batch; the ratio is against the baseline.
| Operation | Values per key | Dictionary<K, List<V>> |
Dictionary<K, List<V>> + lock |
MultiMap |
|---|---|---|---|---|
| Add every pair | 1 | 16.125 μs | 19.323 μs (1.20×) | 22.700 μs (1.41×) |
| Add every pair | 10 | 78.815 μs | 99.808 μs (1.27×) | 142.029 μs (1.80×) |
| Lookup every key | 1 | 1.963 μs | 8.345 μs (4.25×) | 12.896 μs (6.57×) |
| Lookup every key | 10 | 1.742 μs | 9.246 μs (5.31×) | 14.480 μs (8.31×) |
| ContainsPair for every pair | 1 | 3.014 μs | 5.365 μs (1.78×) | 11.027 μs (3.66×) |
| ContainsPair for every pair | 10 | 46.580 μs | 64.731 μs (1.39×) | 146.250 μs (3.14×) |
| Add, then remove every pair | 1 | 23.348 μs | 28.163 μs (1.21×) | 35.219 μs (1.51×) |
| Add, then remove every pair | 10 | 186.702 μs | 232.146 μs (1.24×) | 328.195 μs (1.76×) |
| Lookup every key, 8 reader threads | 1 | 4.282 μs | 52.086 μs (12.18×) | 43.283 μs (10.12×) |
| Lookup every key, 8 reader threads | 10 | 4.144 μs | 53.326 μs (12.88×) | 47.527 μs (11.48×) |
Measured with BenchmarkDotNet 0.15.8 (Release, default job) on an Apple M3 Max, macOS 26.6.2,
.NET 10.0.0 (Arm64 RyuJIT). This is a developer machine, not an isolated lab, so compare the ratios
rather than the absolute times. Raw output, including allocations: benchmarks/results.
What the numbers say:
- Safety has a price on a single thread. A lookup takes about 13 ns in
MultiMap, 8 ns with alockand 2 ns unsynchronized. Two costs add up: the lock itself, and the snapshot, since every read allocates a copy of the bucket (32 bytes for oneintvalue, 64 bytes for ten). The baseline allocates nothing because it returns the live list, which is exactly what makes it unsafe to share. - Under concurrent reads
MultiMapis ahead of thelockversion, but only by 12–20%. Both pay for the copy on every read, so letting readers run in parallel helps less than it does for BiMap, whose lookups do not allocate. - Bucket scans are the slowest path.
ContainsPairis about 3× the baseline.MultiMapcompares through the configuredIEqualityComparer<TValue>(it supports custom comparers), whileList<int>.Containsuses a vectorized search for primitive types. - Writes cost 1.4–1.8× the unsynchronized dictionary.
If a single thread owns the map, the hand-rolled dictionary is faster. MultiMap is for a map that is
shared between threads, or handed to code that expects an ILookup.
Run them yourself:
dotnet run -c Release --project benchmarks/MultiMap.Benchmarks -- --filter '*'MIT — see LICENSE.