忽略Dictionary ContainsKey中的大小写,其中键是动态的

时间:2018-07-26 15:19:33

标签: c#

我有一个Dictionary<dynamic, string>,在检查字典中是否包含键时,如果键是字符串,我想忽略大小写。这可能吗?

2 个答案:

答案 0 :(得分:1)

您可以在Dictionary上添加扩展名,该扩展名确定键是否为字符串类型,如果是,则使用不区分大小写的比较;否则,它将使用默认比较。

public static class DictionaryExtension
{
    public static bool ContainsKeyIgnoreCase<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
    {
        bool? keyExists;

        var keyString = key as string;
        if (keyString != null)
        {
            // Key is a string.
            // Using string.Equals to perform case insensitive comparison of the dictionary key.
            keyExists =
                dictionary.Keys.OfType<string>()
                .Any(k => string.Equals(k, keyString, StringComparison.InvariantCultureIgnoreCase));
        }
        else
        {
            // Key is any other type, use default comparison.
            keyExists = dictionary.ContainsKey(key);
        }

        return keyExists ?? false;
    }
}

然后您可以像这样使用它:

var foo = new Foo();
var dictionary =
    new Dictionary<dynamic, string>
    {
        { 1, "One" },     // key is numeric
        { "Two", "Two" }, // key is string
        { foo, "Foo" }    // key is object
    };

dictionary.ContainsKeyIgnoreCase("two");     // Returns true
dictionary.ContainsKeyIgnoreCase("TwO");     // Returns true
dictionary.ContainsKeyIgnoreCase("aBc");     // Returns false
dictionary.ContainsKeyIgnoreCase(1);         // Returns true
dictionary.ContainsKeyIgnoreCase(2);         // Returns false
dictionary.ContainsKeyIgnoreCase(foo);       // Returns true
dictionary.ContainsKeyIgnoreCase(new Foo()); // Returns false

注意:
上面的扩展示例正在使用StringComparer.InvariantCultureIgnoreCase。您可能需要根据需要修改比较。

答案 1 :(得分:0)

没有合理的方法可以在区分大小写的哈希图上实现不区分大小写的获取。

尽管您可以使用现有的区分大小写的字典的内容创建一个新的不区分大小写的字典(如果您确定没有大小写冲突):-

it

如果有效,请告诉我。