首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# HashTable 實作與進階操作(二)

     編輯:關於C語言

遍歷 HashTable

foreach (DictionaryEntry de in ht) {
    Console.WriteLine($"Key: {de.Key}, Value: {de.Value}");
}

排序輸出(HashTable 本身不支援排序)

ArrayList keys = new ArrayList(ht.Keys);
keys.Sort(); // 字母順序
foreach (string key in keys) {
    Console.WriteLine($"{key}: {ht[key]}");
}

SortedList:自動排序的鍵值集合

SortedList sl = new SortedList();
sl["c"] = 41; sl["a"] = 42; sl["d"] = 11; sl["b"] = 13;
foreach (DictionaryEntry de in sl) {
    Console.WriteLine($"{de.Key}, {de.Value}");
}
// 輸出: a,42  b,13  c,41  d,11 (依 Key 排序)

比較

特性HashtableSortedList
Key 排序無序自動排序
查找效能O(1)O(log n)
記憶體較小較大(維護兩個陣列)

需頻繁排序輸出時用 SortedList;純查找高效能用 Hashtable。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved