-2

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".

GoCurry
  • 899
  • 11
  • 31

3 Answers3

1

As soon as I posted the question I realized the answer is to simply use a case insensitive dictionary...

var names = new Dictionary<string, string>StringComparer.OrdinalIgnoreCase)
{
    {"Alice","Alice"},
    {"Bob","Bob"},
    {"Charles","Charles"},
}
GoCurry
  • 899
  • 11
  • 31
0

Well it's not terribly pretty but you could use:

string match = names.FirstOrDefault(n => names.Comparer.Equals(n,"aLice"));

Or use a Dictionary<string, string> instead, which is better at retrieving values. HashSet is good at storing unique values, but there's not a great mechanism to get the "matching" value out of it.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

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
poke
  • 369,085
  • 72
  • 557
  • 602