LINQ in Practice · Lesson 7

Dictionary boundaries

Decide how duplicate keys should behave.

How it works

ToDictionary creates a lookup from a sequence and requires each generated key to be unique according to its comparer. It throws when two source elements produce equal keys, which is often the right signal for a violated uniqueness assumption. This lesson uses TryAdd to express another explicit policy: preserve the first item and report a duplicate. Neither policy is universally correct.

A catalog may reject duplicates, an import may merge them, and a report may need grouping. Choose the behavior at the boundary where the data enters the system, and document which occurrence wins if one must win.

Replace the second TryAdd with assignment through the indexer and predict the stored value. Explain when first-wins, last-wins, summing, and rejection are appropriate policies.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var totals = new Dictionary<string, int>(StringComparer.Ordinal);
Console.WriteLine(totals.TryAdd("A", 3));
Console.WriteLine(totals.TryAdd("A", 9));
Console.WriteLine(totals["A"]);

Expected output

True
False
3
Try this
Duplicate policy belongs in the program, not in an accidental exception.