Case-INsensitive Dictionary with string key-type in C#

自古美人都是妖i 提交于 2019-11-26 12:07:42

问题


If I have a Dictionary<String,...> is it possible to make methods like ContainsKey case-insensitive?

This seemed related, but I didn\'t understand it properly: c# Dictionary: making the Key case-insensitive through declarations


回答1:


This seemed related, but I didn't understand it properly: c# Dictionary: making the Key case-insensitive through declarations

It is indeed related. The solution is to tell the dictionary instance not to use the standard string compare method (which is case sensitive) but rather to use a case insensitive one. This is done using the appropriate constructor:

var dict = new Dictionary<string, YourClass>(
        StringComparer.InvariantCultureIgnoreCase);

The constructor expects an IEqualityComparer which tells the dictionary how to compare keys.

StringComparer.InvariantCultureIgnoreCase gives you an IEqualityComparer instance which compares strings in a case-insensitive manner.




回答2:


var myDic = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
myDic.Add("HeLlo", "hi");

if (myDic.ContainsKey("hello"))
    Console.WriteLine(myDic["hello"]);



回答3:


There are few chances where your deal with dictionary which is pulled from 3rd party or external dll. Using linq

YourDictionary.Any(i => i.KeyName.ToLower().Contains("yourstring")))




回答4:


I just ran into the same kind of trouble where I needed a caseINsensitive dictionary in a ASP.NET Core controller.

I wrote an extension method which does the trick. Maybe this can be helpful for others as well...

public static IDictionary<string, TValue> ConvertToCaseInSensitive<TValue>(this IDictionary<string, TValue> dictionary)
{
    var resultDictionary = new Dictionary<string, TValue>(StringComparer.InvariantCultureIgnoreCase);
    foreach (var (key, value) in dictionary)
    {
        resultDictionary.Add(key, value);
    }

    dictionary = resultDictionary;
    return dictionary;
}

To use the extension method:

myDictionary.ConvertToCaseInSensitive();

Then get a value from the dictionary with:

myDictionary.ContainsKey("TheKeyWhichIsNotCaseSensitiveAnymore!");


来源:https://stackoverflow.com/questions/13988643/case-insensitive-dictionary-with-string-key-type-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!