Sometimes user names are case-insensitive—upper and lower letters are treated as equal. We implement a case-insensitive string Dictionary.
Requirements. Suppose we want to add a string "cat" to a Dictionary. But we want to be able to look up "CAT" and "Cat" also. The insensitive Dictionary is a solution.
cat ->
cat,
CAT,
Cat
Example. The Dictionary class has several overloaded constructors. Here we use one that accepts a generic IEqualityComparer parameter.
Info IEqualityComparer is an interface. It is used by Dictionary to acquire hash codes and compare keys.
ToLower. To normalize string data in a Dictionary, you can call ToLower when adding or accessing keys. But this will cause additional allocations and more GC pressure.
Summary. We implemented a case-insensitive string Dictionary. You do not need a custom IEqualityComparer, although if your requirements are slightly unusual this can help.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 10, 2024 (edit).