不区分大小写辞典串键式在C# [英] Case-INsensitive Dictionary with string key-type in C#

查看:309
本文介绍了不区分大小写辞典串键式在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个词典<弦乐,...> 是有可能使像的containsKey 方法不区分大小写?

这似乎是有关,但我没有正确理解它:<一href=\"http://stackoverflow.com/questions/6676245/c-sharp-dictionary-making-the-key-case-insensitive-through-declarations\">c#词典:使钥匙不区分大小写通过声明


解决方案

  

这似乎是有关,但我没有正确理解它:C#词典:使钥匙不区分大小写通过声明


这确实有关。解决的办法是告诉字典实例不使用标准的字符串比较方法(区分大小写),而是使用不区分大小写的。这是使用适当的构造完成的:

  VAR字典=新词典&LT;字符串,YourClass&GT;(
        StringComparer.InvariantCultureIgnoreCase);

构造期望一个<一个href=\"http://msdn.microsoft.com/en-us/library/ms132151%28v=vs.80%29.aspx\"><$c$c>IEqualityComparer它告诉词典如何对键进行比较。

<一个href=\"http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx\"><$c$c>StringComparer.InvariantCultureIgnoreCase给你这不区分大小写的方式比较字符串的的IEqualityComparer 实例。

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

解决方案

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.

这篇关于不区分大小写辞典串键式在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆