首頁 >後端開發 >C++ >為什麼 C# 字典不保證元素順序,如何確保按字母順序排序?

為什麼 C# 字典不保證元素順序,如何確保按字母順序排序?

Mary-Kate Olsen
Mary-Kate Olsen原創
2025-01-17 19:01:10426瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn