您可以在
Dictionary
它确定键是否为string类型,如果是,则使用不区分大小写的比较;否则,则使用默认比较。
public static class DictionaryExtension
{
public static bool ContainsKeyIgnoreCase(this Dictionary 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()
.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
{
{ 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