我有一个 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/