首页 > 后端开发 > C++ > 为什么 C# 字典不保证元素顺序,如何确保按字母顺序排序?

为什么 C# 字典不保证元素顺序,如何确保按字母顺序排序?

Mary-Kate Olsen
发布: 2025-01-17 19:01:10
原创
382 人浏览过

Why Doesn't C# Dictionary Guarantee Element Order, and How Can I Ensure Alphabetical Ordering?

理解 C# 字典排序(或缺乏)

许多 C# 开发人员错误地认为 Dictionary 元素按插入顺序返回。 这是不正确的。以下示例说明了这一点:

<code class="language-csharp">// Dictionary declaration
private Dictionary<string, string> _Dictionary = new Dictionary<string, string>();

// Add elements
_Dictionary.Add("orange", "1");
_Dictionary.Add("apple", "4");
_Dictionary.Add("cucumber", "6");
_Dictionary["banana"] = "7";
_Dictionary["pineapple"] = "7";

// Iterate and observe the order (non-deterministic)
foreach (KeyValuePair<string, string> kvp in _Dictionary)
{
    Trace.Write(String.Format("{0}={1}", kvp.Key, kvp.Value));
}</code>
登录后复制

输出是不可预测的,因为Dictionary使用哈希表,它优先考虑高效的键查找而不是维护插入顺序。 迭代的顺序无法保证并且会有所不同。

使用 SortedDictionary 强制按字母顺序排列

如果您需要按字母顺序排序的元素,请使用 SortedDictionary 代替。 此类根据键的比较器维护排序顺序(默认为字符串字母顺序)。

<code class="language-csharp">// SortedDictionary declaration
private SortedDictionary<string, string> _SortedDictionary = new SortedDictionary<string, string>();

// Add elements
_SortedDictionary.Add("orange", "1");
_SortedDictionary.Add("apple", "4");
_SortedDictionary.Add("cucumber", "6");
_SortedDictionary.Add("banana", "7");
_SortedDictionary.Add("pineapple", "7");

// Iterate and observe the alphabetical order
foreach (KeyValuePair<string, string> kvp in _SortedDictionary)
{
    Trace.Write(String.Format("{0}={1}", kvp.Key, kvp.Value));
}</code>
登录后复制

这将始终产生按字母顺序排序的输出。 请记住,与 SortedDictionary 相比,Dictionary 具有性能开销,因此仅在顺序必不可少时才使用它。

以上是为什么 C# 字典不保证元素顺序,如何确保按字母顺序排序?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板