C# 字典 : making the Key case-insensitive through declarations

标签 c# dictionary case-insensitive

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

问题是 Guid我的源数据中的键为 VarChar , 所以现在是 "923D81A0-7B71-438d-8160-A524EA7EFA5E" 的关键与 "923d81a0-7b71-438d-8160-a524ea7efa5e" 不同(使用 Guid 时没有问题)。

.NET 框架真正好的(和甜蜜的)是我可以做到这一点:

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

而且效果很好。但是嵌套的字典呢?像下面这样:

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

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

最佳答案

当你向外部字典添加一个元素时,你可能会创建一个新的嵌套字典实例,此时添加它,使用 overloaded constructor这需要 IEqualityComparer<TKey> .

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


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

关于C# 字典 : making the Key case-insensitive through declarations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6676245/

相关文章:

python - 在字典中删除\n

variables - .emacs 中区分大小写的 setq 没有效果

java - 如何使我的字符串比较不区分大小写?

emacs - 如何使 describe-function "C-h f"默认不区分大小写

C# 控制台应用程序 session /存储

c# - 如何解决 - 无法使用 Automapper 将 Generic.List 转换为 Linq.IQueryable?

c# - C#中字符串中字符的左侧

c# - 如果值在以前的记录中,则在 linq 查询中选择 null

python - "Adding"Python 中的字典?

python - 简化/优化 for 循环链