C# Collection
数组与集合不同的适用范围:
数组:数组最适用于创建和使用固定数量的强类型化对象。
集合:集合提供更灵活的方式来使用对象组。 与数组不同,你使用的对象组随着应用程序更改的需要动态地放大和缩小。 对于某些集合,你可以为放入集合中的任何对象分配一个密钥,这样你便可以使用该密钥快速检索此对象。
集合的类型
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
方法将导致已移除的元素后的元素的索引值减小。
待续...