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