c# - SortedDictionary 参数异常 : "Æ" and "AE" considered the same keys

标签 c# .net dictionary unique sorteddictionary

我试图使用 SortedDictionary 来存储文件中的一些数据,但遇到了一堆非常奇怪的键重复异常。我想出了下一个重现我的问题的代码示例:

var dict = new SortedDictionary<string, string>();
dict.Add("Æ", "qwerty"); // "aesc" (aka "ash"), single symbol
Console.WriteLine(dict["AE"]); // outputs "qwerty" for two-symbol string "AE"
dict.Add("AE", ""); // ArgumentException: An entry with the same key already exists.

This code on .NET Fiddle

虽然通常的词典不会发生这种情况,但我最终决定改用它。但我仍然想知道为什么排序后会出现问题?不幸的是,尽管 MS 最近开放了一些 .NET 源代码,但我自己无法通过谷歌搜索答案(得到了很多与 AES 相关的噪音)并且无法调试到 SortedDictionary 的代码。

这个类似乎隐式地运行了一些字符串预处理/规范化函数,但我不敢相信这是一个真正的原因。

知道为什么会这样吗?提前致谢!

最佳答案

这是因为文化。尝试 new SortedDictionary(StringComparer.Ordinal) ,例如。

Dictionary 行为不同的原因是它使用 EqualityComparer<TKey>.Default而 SortedDictionary 使用 Comparer<TKey>.Default .

关于c# - SortedDictionary 参数异常 : "Æ" and "AE" considered the same keys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30477315/

相关文章:

c# - Regex.Match整个单词

c# - 以英寸为单位转换字体大小

c# - 是否有不区分大小写的 string.Replace 替代方法?

python - 通过字典键进行动态操作

c# - 重构 If else 树

c# - 我可以从后面的 C# 代码更新 WPF 绑定(bind)的值吗?

c# - MS Office COM 与多个 UAC 用户的互操作和线程安全

python - 将一对列表对象转换为包含重复项的字典

c# - 用于键值查找的更简单的数据结构?

c# - 找不到类型或命名空间名称 'Stack'(仅适用于 .NET 4.0)