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

标签 c# .net hashtable

我不区分大小写 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/

相关文章:

.net - 格式 double 类型

哈希问题的 Perl 哈希

c# - 将属性传递给 C#、EF 中的函数

c# - 从数据库中过滤 MVC SelectList

c# - 在 MVC 上执行编辑时如何保留某些字段的原始值?

c# - 设置表格最小尺寸

java - 如何将哈希表发送到我的客户端套接字?

c - 重新分配错误: realloc(): invalid next size

c# - 如何在c#中替换字符串之间的某些字符?

c# - 检查值是否已经存在