在不区分大小写的HashSet <string>中获取值

Mik*_*nov 4 .net c# hashtable

我不区分大小写HashSet<string>:

private HashSet<string> a = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
Run Code Online (Sandbox Code Playgroud)

我很好奇,如果我现在可以在实际情况下提取字符串.我需要的伪代码:

return a.Contains(word) ? a[word] : null;
Run Code Online (Sandbox Code Playgroud)

(只是一个伪代码,它不会工作)

例如,我在HashSet中有字符串" TestXxX ".我需要将"testxxx"(或"tEsTXXx")作为输入并返回" TestXxX "的代码.

我目前的解决方法是使用Dictionary<string,string>而是为键和值添加相同的值.这显然不优雅,并且实际需要消耗2倍的内存.

Kir*_*huk 6

你可以覆盖 KeyedCollection

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

    }

    protected override string GetKeyForItem(string item)
    {
        return item;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

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

Console.WriteLine(keyed["tEsTXXx"]);
Run Code Online (Sandbox Code Playgroud)