C#字典:通过声明使Key不区分大小写


74

我有Dictionary<string, object>字典。它曾经是,Dictionary<Guid, object>但是其他“标识符”已经发挥作用,并且现在将键作为字符串处理。

问题是Guid来自我的源数据的键是VarChar,所以现在的键"923D81A0-7B71-438d-8160-A524EA7EFA5E""923d81a0-7b71-438d-8160-a524ea7efa5e"(与Guids时不是问题)不同。

.NET框架的真正优点(也是很好的方面)是我可以这样做:

Dictionary<string, CustomClass> _recordSet = new Dictionary<string, CustomClass>(
    StringComparer.InvariantCultureIgnoreCase);

而且效果很好。但是嵌套字典呢?如下所示:

Dictionary<int, Dictionary<string, CustomClass>> _customRecordSet 
    = new  Dictionary<int, Dictionary<string, CustomClass>>();

我如何在这样的嵌套字典上指定字符串比较器?


26
只是一个提示,您可能需要重新考虑使用StringComparer.InvariantCultureIgnoreCase。该比较器很慢,因为它将使用字符类比较字符串以克服跨文化差异。这意味着该单词Straße将被视为等于,Strasse反之亦然。我假设您不希望出现这种情况,并且如果性能至关重要(如果您正在数据库上实现缓存层之类的功能),那么使用会更好StringComparer.OrdinalIgnoreCase。顺序比较器是.NET框架可以提供的最快的字符串比较器。
Ivaylo Slavov


2
真的是@ avs099吗?您链接到的帖子比此帖子年轻一岁。你甚至注意到了吗?
AustinWBryan'1

3
@AustinWBryan:“可能重复”是一种清理方法-关闭类似的问题,并为每个问题提供最佳答案。日期不是必需的。请参阅我是否应该投票关闭重复的问题,即使它是一个新问题,并且有更多最新答案?
Michael Freidgeim

Answers:


80

当您将元素添加到外部字典中时,您可能会创建一个嵌套字典的新实例,在这一点上添加它,并使用带有的重载构造函数IEqualityComparer<TKey>

_customRecordSet.Add(0, new Dictionary<string, CustomClass>(StringComparer.InvariantCultureIgnoreCase));


2017年8月3日更新:有趣的是,我读过某个地方(我想在“编写高性能.NET代码”中),StringComparer.OrdinalIgnoreCase只是想忽略字符的大小写时,它的效率更高。但是,这对我自己完全没有根据,因此YMMV。


8

您将必须初始化嵌套字典才能使用它们。只需使用上面的代码即可。

基本上,您应该具有以下代码:

public void insert(int int_key, string guid, CustomClass obj)
{
    if (_customRecordSet.ContainsKey(int_key)
         _customRecordSet[int_key][guid] = obj;
    else
    {
         _customRecordSet[int_key] = new Dictionary<string, CustomClass> 
                                     (StringComparer.InvariantCultureIgnoreCase);
         _customRecordSet[int_key][guid] = obj;
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.