Search code examples
c#stringcase-sensitivecase-insensitive

C# - How can I correct string case by using HashSet<string>


Given a hash set such as:

HashSet<string> names = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
    "Alice",
    "Bob",
    "Charles",
}

How can I use this hash set to find the mapped value of a case insensitive string? For example, if I have a string "aLICe", I want to be able to find "Alice".


Solution

  • If I understand you correctly, you want to get the original value that was added to the hash set. So since “Alice” is the value in the hash set, you want to get that for inputs of “alice”, or “aLICe”.

    Efficiently, this is not possible with a hash set. You would have to loop through the elements of the hash set to find the original value, making it as efficient as a list.

    What you could do is have a dictionary instead which allows you to have a case-insensitive lookup but return the real value instead:

    var names = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
    {
        { "Alice", "Alice" },
        { "Bob", "Bob" },
        { "Charles", "Charles" }
    };
    
    Console.WriteLine(names["alice"]); // Alice
    Console.WriteLine(names["aLICe"]); // Alice