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

后端 未结 5 1942
余生分开走
余生分开走 2020-11-30 23:53

If I have a Dictionary is it possible to make methods like ContainsKey case-insensitive?

This seemed related, but I didn\

5条回答
  •  抹茶落季
    2020-12-01 00:35

    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(
            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.

提交回复
热议问题