數組與集合不同的適用范圍:
數組:數組最適用於創建和使用固定數量的強類型化對象。
集合:集合提供更靈活的方式來使用對象組。 與數組不同,你使用的對象組隨着應用程序更改的需要動態地放大和縮小。 對於某些集合,你可以為放入集合中的任何對象分配一個密鑰,這樣你便可以使用該密鑰快速檢索此對象。
集合的類型
System.Collections.Generic 類
Generic 泛型
類 | 說明 |
---|---|
Dictionary | 表示基於鍵進行組織的鍵/值對的集合。 |
List | 表示可按索引訪問的對象的列表。 提供用於對列表進行搜索、排序和修改的方法。 |
Queue | 表示對象的先進先出 (FIFO) 集合。 |
SortedList | 表示基於相關的 IComparer 實現按鍵進行排序的鍵/值對的集合。 |
Stack | 表示對象的后進先出 (LIFO) 集合。 |
System.Collections.Concurrent 類
Concurrent 並發
只要多個線程同時訪問集合,就應使用 System.Collections.Concurrent 命名空間中的類。
System.Collections 類
已經過時,盡可能不要用!
只要可能,則應使用 System.Collections.Generic 命名空間或 System.Collections.Concurrent 命名空間中的泛型集合,而不是
System.Collections
命名空間中的舊類型。推薦使用泛型版本和並發版本的集合,因為它們的類型安全性很高,並且還經過了其他改進。
選擇集合
我要…… | 泛型集合選項 |
---|---|
將項存儲為鍵/值對以通過鍵進行快速查找 | Dictionary |
按索引訪問項 | List |
使用項先進先出 (FIFO) | Queue |
使用數據后進先出 (LIFO) | Stack |
按順序訪問項 | LinkedList |
已排序的集合 | SortedList |
數學函數的一個集 | HashSet SortedSet |
泛型集合的算法復雜性
Runtime Complexity of .NET Generic Collection
Internal Implement- ation | Add/insert | Add beyond capacity | Queue/Push | Dequeue/ Pop/Peek | Remove/ RemoveAt | Item[index]/ElementAt(index) | GetEnumerator | Contains(value)/IndexOf/ContainsValue/Find | |
---|---|---|---|---|---|---|---|---|---|
List | Array | O(1) to add, O(n) to insert | O(n) | - | - | O(n) | O(1) | O(1) | O(n) |
LinkedList | Doubly linked list | O(1), before/after given node | O(1) | O(1) | O(1) | O(1), before/after given node | O(n) | O(1) | O(n) |
Stack | Array | O(1) | O(n) | O(1) | O(1) | - | - | O(1) | O(n) |
Queue | Array | O(1) | O(n) | O(1) | O(1) | - | - | O(1) | O(n) |
Dictionary | Hashtable with links to another array index for collision | O(1), O(n) if collision | O(n) | - | - | O(1), O(n) if collision | O(1), O(n) if collision | O(1) | O(n) |
HashSet | Hashtable with links to another array index for collision | O(1), O(n) if collision | O(n) | - | - | O(1), O(n) if collision | O(1), O(n) if collision | O(1) | - |
SortedDictionary | Red-black tree | O(log n) | O(log n) | - | - | O(log n) | O(log n) | O(log n) | O(n) |
SortedList | Array | O(n), O(log n) if added to end of list | O(n) | - | - | O(n) | O(log n) | O(1) | O(n) |
SortedSet | Red-black tree | O(log n) | O(log n) | - | - | O(log n) | O(log n) | O(log n) | - |
Note:
-
Dictionary
Add, remove and item[i] has expected O(1) running time
-
HashSet
Add, remove and item[i] has expected O(1) running time
集合設計分析
常用集合的注意事項
List<T>
刪除元素的順序
使用以降序進行循環訪問的 for
語句,而非 foreach
語句。這是因為 RemoveAt
方法將導致已移除的元素后的元素的索引值減小。
待續...