泛型字典不区分大小写的访问 [英] Case insensitive access for generic dictionary

查看:145
本文介绍了泛型字典不区分大小写的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用托管的DLL的应用程序。其中一个的DLL返回一个通用的字典:

I have an application that use managed dlls. One of those dlls return a generic dictionary:

Dictionary<string, int> MyDictionary;  



本字典包含大小写键。

The dictionary contains keys with upper and lower case.

在另一边我得到的潜在键(串)的列表,但是我不能保证的情况下。我试图让使用按键字典中的价值。但是,当然,因为我有一个不匹配的情况下会失败:

On another side I am getting a list of potential keys (string) however I cannot guarantee the case. I am trying to get the value in the dictionary using the keys. But of course the following will fail since I have a case mismatch:

bool Success = MyDictionary.TryGetValue( MyIndex, out TheValue );  



我希望在TryGetValue将有一个的忽略大小写的像中提到的标志 DOC ,但似乎这是无效的通用词典。

I was hoping the TryGetValue would have an ignore case flag like mentioned in the MSDN doc, but it seems this is not valid for generic dictionaries.

有没有办法让该字典忽略的关键案例的价值?
难道还有比用正确的创建词典的新副本一个更好的解决办法的 StringComparer.OrdinalIgnoreCase 的参数?

Is there a way to get the value of that dictionary ignoring the key case? Is there a better workaround than creating a new copy of the dictionary with the proper StringComparer.OrdinalIgnoreCase parameter?

推荐答案

有没有办法在您尝试得到一个价值点到指定 StringComparer 。如果你仔细想想,富.GetHashCode()foo的.GetHashCode()是完全不同的所以有您可以实现区分大小写的哈希地图上不区分大小写的没有得到合理的方式。

There's no way to specify a StringComparer at the point where you try to get a value. If you think about it, "Foo".GetHashCode() and "foo".GetHashCode() are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.

您可以,但是,创建了第一个不区分大小写的字典场所使用: -

You can, however, create a case-insensitive dictionary in the first place using:-

var caseInsensitiveDictionary = new Dictionary<string, int>(
  StringComparer.OrdinalIgnoreCase);



(这本词典然后使用的GetHashCode()实施关于 StringComparer.OrdinalIgnoreCase ,使得 comparer.GetHashCode(富)比较器.GetHashcode(富)给你相同的值)

(This dictionary then uses the GetHashCode() implementation on StringComparer.OrdinalIgnoreCase such that comparer.GetHashCode("Foo") and comparer.GetHashcode("foo") give you the same value)

你多久需要得到字典从你的依赖?如果你只有一次,你可以很轻松地创建旧的内容,新的不区分大小写的字典: -

How often do you need to get the dictionary from your dependency? If you only get it once, you can quite easily create a new case-insensitive dictionary with the contents of the old one:-

MyDictionary = new Dictionary<string, int>(
  MyDictionary, StringComparer.OrdinalIgnoreCase);

这篇关于泛型字典不区分大小写的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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