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.
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"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With