Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value in case-insensitive HashSet<string>

Tags:

c#

.net

hashtable

I have case-insensitive HashSet<string>:

private HashSet<string> a = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);

I'm curious if I can now extract the string in the actual case. Pseudo code of what I need:

return a.Contains(word) ? a[word] : null;

(just a pseudo code, it won't work)

For example, I have string "TestXxX" in the HashSet. I need for the code which gets "testxxx" (or "tEsTXXx") as input and returns "TestXxX".

My current workaround is to use Dictionary<string,string> instead and put the same value for both key and value. This is obviously not elegant and consumes 2x memory as it actually needs.

like image 698
Mike Keskinov Avatar asked Jun 02 '15 23:06

Mike Keskinov


1 Answers

You can override KeyedCollection

public class Keyed : KeyedCollection<string, string>
{
    public Keyed(IEqualityComparer<string> comparer) : base(comparer)
    {

    }

    protected override string GetKeyForItem(string item)
    {
        return item;
    }
}

Then use it:

var keyed = new Keyed(StringComparer.InvariantCultureIgnoreCase);
keyed.Add("TestXxX");

Console.WriteLine(keyed["tEsTXXx"]);
like image 160
Kirill Polishchuk Avatar answered Oct 05 '22 22:10

Kirill Polishchuk