我不区分大小写 HashSet<string>
:
private HashSet<string> a = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
我很好奇我现在是否可以在实际情况下提取字符串。我需要的伪代码:
return a.Contains(word) ? a[word] : null;
(只是一个伪代码,不会起作用)
例如,我在 HashSet 中有字符串“TestXxX”。我需要获取“testxxx”(或“tEsTXXx”)作为输入并返回“TestXxX”的代码。
我目前的解决方法是使用 Dictionary<string,string>
相反,并为键和值设置相同的值。这显然不优雅,并且消耗了实际需要的 2 倍内存。
最佳答案
您可以覆盖 KeyedCollection
public class Keyed : KeyedCollection<string, string>
{
public Keyed(IEqualityComparer<string> comparer) : base(comparer)
{
}
protected override string GetKeyForItem(string item)
{
return item;
}
}
然后使用它:
var keyed = new Keyed(StringComparer.InvariantCultureIgnoreCase);
keyed.Add("TestXxX");
Console.WriteLine(keyed["tEsTXXx"]);
关于c# - 在不区分大小写的 HashSet<string> 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30608120/