繁体   English   中英

c# 字典:通过声明使密钥不区分大小写

[英]c# Dictionary: making the Key case-insensitive through declarations

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

问题是我的源数据中的Guid键是VarChar ,所以现在“923D81A0-7B71-438d-8160-A524EA7EFA5E”的键与"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>>();

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

当您将元素添加到外部字典时,您可能会创建嵌套字典的新实例,此时添加它,使用采用IEqualityComparer<TKey>重载构造函数

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


2017 年 8 月 3日更新:有趣的是,我在某处读到(我认为在“编写高性能 .NET 代码”中) StringComparer.OrdinalIgnoreCase在只想忽略字符大小写时更有效。 然而,这完全是我自己没有根据的,所以YMMV。

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

基本上,你应该有一些这样的代码:

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM