C#
dictionary
mapping
data structures
programming

Map two lists into a dictionary in C

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Mapping one list of keys and one list of values into a dictionary is a common transformation in C sharp applications. The basic operation is easy, but robust code must define behavior for length mismatch, duplicate keys, and null keys. Good mapping utilities make those rules explicit and testable.

Basic Mapping with Zip and ToDictionary

For clean input with equal lengths and unique keys, Zip is concise.

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5var keys = new List<string> { "a", "b", "c" };
6var values = new List<int> { 10, 20, 30 };
7
8var dict = keys.Zip(values, (k, v) => new { k, v })
9               .ToDictionary(x => x.k, x => x.v);
10
11Console.WriteLine(dict["b"]);

This is readable for straightforward datasets.

Guard Against Length Mismatch

Zip truncates to the shorter list without warning. If truncation is unacceptable, enforce equal lengths first.

csharp
1if (keys.Count != values.Count)
2{
3    throw new InvalidOperationException("Keys and values must have equal length.");
4}

Failing fast prevents silent data loss.

Define Duplicate Key Policy

ToDictionary throws on duplicate keys. Decide one policy intentionally:

  • Fail on duplicate keys.
  • Last value wins.
  • First value wins.
  • Aggregate values into list.

Example with last value wins:

csharp
1var safe = new Dictionary<string, int>();
2for (int i = 0; i < Math.Min(keys.Count, values.Count); i++)
3{
4    safe[keys[i]] = values[i];
5}

Document policy because downstream behavior depends on it.

Build a Reusable Generic Helper

Centralize mapping logic in helper method.

csharp
1public static Dictionary<TKey, TValue> ZipToDictionary<TKey, TValue>(
2    IReadOnlyList<TKey> keys,
3    IReadOnlyList<TValue> values,
4    bool requireEqualLength = true)
5    where TKey : notnull
6{
7    if (requireEqualLength && keys.Count != values.Count)
8        throw new ArgumentException("Mismatched key/value lengths.");
9
10    int n = Math.Min(keys.Count, values.Count);
11    var result = new Dictionary<TKey, TValue>(n);
12
13    for (int i = 0; i < n; i++)
14        result[keys[i]] = values[i];
15
16    return result;
17}

One helper ensures consistent behavior across modules.

Handle Null and Key Normalization

If keys come from external sources, normalize before mapping. Typical steps:

  • Trim whitespace.
  • Apply case normalization if domain allows.
  • Reject null or empty keys.
csharp
string NormalizeKey(string key) => key.Trim().ToLowerInvariant();

Normalization reduces accidental duplicates caused by formatting differences.

Performance Considerations

For hot paths and large lists, loop-based mapping is often faster and allocates less than chained LINQ operations. Measure performance when mapping runs frequently.

Choose readability first for non-critical paths, then optimize based on profile data.

Add Mapping Quality Telemetry

In production ETL and integration flows, record metrics:

  • Total key count.
  • Total mapped pairs.
  • Duplicate key count.
  • Mismatch count.

These metrics help detect upstream data changes before they break business logic.

Testing Strategy

Include tests for:

  1. Equal lengths and unique keys.
  2. Unequal lengths.
  3. Duplicate keys under selected policy.
  4. Empty lists.
  5. Null key handling.

Explicit tests prevent helper regressions and clarify intended behavior.

Choosing Comparers for String Keys

If keys are strings and case-insensitive lookup is required, create dictionary with explicit comparer.

csharp
var dictCaseInsensitive = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

Comparer choice should match domain rules so lookup behavior is predictable in all environments.

Common Pitfalls

  • Using Zip and forgetting silent truncation behavior.
  • Assuming keys are unique when source data is dirty.
  • Not defining duplicate-key resolution policy.
  • Ignoring null or empty key validation.
  • Overusing LINQ in high-frequency mapping paths without profiling.

Summary

  • 'Zip and ToDictionary works well for clean equal-length input.'
  • Add explicit checks for length mismatch and duplicate keys.
  • Centralize behavior in generic helper methods.
  • Normalize keys when data comes from external systems.
  • Cover mapping edge cases with focused unit tests.

Course illustration
Course illustration

All Rights Reserved.