Real Web Developers

Case-insensitive Dictionary access in C#

Author
Scott Rickman
Last updated

Case-insensitive dictionary access is achieved by passing a Comparer that's used to compare a key used to access the dictionary with the keys in the dictionary.

In the example below the key passed to GetValueOrDefault("DOG") is compared to the keys in the dictionary in an ordinal case-insensitive manner.

The same comparer is used when accessing the dictionary using cache["dOg"].

This is particularily useful if the key is user input or from another system i.e. an API call or message subscription.

    
namespace RealWebDevelopers;

using System;
using System.Collections.Generic;

public static class Program
{
    private static readonly Dictionary cache = new(StringComparer.OrdinalIgnoreCase)
    {
        {
            "dog", "woof"
        },
        {
            "cat", "meow"
        },
    };

    public static void Main(string[] args)
    {
        Console.Write(cache.GetValueOrDefault("dog"));
        Console.Write(cache.GetValueOrDefault("Dog"));
    }
}