c#list和dictionary
时间: 2025-05-17 09:17:42 浏览: 22
### C# 中 `List` 和 `Dictionary` 的区别及用法
#### 数据结构特性
`List<T>` 是一种基于数组实现的动态集合,允许存储任意数量的元素并支持按索引快速访问。它适用于需要频繁遍历或随机访问元素的场景[^5]。
相比之下,`Dictionary<TKey, TValue>` 是键值对的集合,内部使用哈希表实现。它的主要优势在于通过键查找对应的值时具有接近 O(1) 的时间复杂度,因此非常适合用于需要高效查找的数据处理场合[^1]。
#### 存储方式
`List<T>` 只能存储单一维度的元素序列,而这些元素可以通过整数索引来定位。例如:
```csharp
var list = new List<int> { 1, 2, 3 };
int value = list[0]; // 访问第一个元素
```
`Dictionary<TKey, TValue>` 则以键值对的形式存储数据,其中键必须唯一且不可变。这使得它可以更灵活地表示关联关系。例如:
```csharp
var dictionary = new Dictionary<string, int>
{
{ "one", 1 },
{ "two", 2 }
};
int value = dictionary["one"]; // 根据键获取对应值
```
#### 性能比较
当涉及到大量数据的操作时,两者的性能差异显著。如果仅需线性迭代或者按照固定位置检索,则 `List<T>` 更加适合;但如果要执行大量的查找操作(尤其是依据特定条件),那么 `Dictionary<TKey, TValue>` 显著优于前者因为其利用了散列机制来加速匹配过程[^4]。
另外,在插入新项方面两者也有差别——向未满容量下的列表尾部追加一项成本很低,但在字典里新增条目可能引发重新分配内存空间的情况发生从而影响效率[^2]。
#### 使用建议
- 如果应用场景主要是围绕着简单的枚举或是维持对象间的相对次序展开的话,应该优先考虑采用 Lists;
- 对于那些强调高速存取指定记录的应用程序来说,则应当倾向于选用 Dictionaries 来构建解决方案[^3]。
### 示例代码展示
以下是分别针对这两种容器的一些基本操作演示:
对于 `List<T>`:
```csharp
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var numbers = new List<int>();
// 添加元素到列表中
numbers.Add(7);
numbers.AddRange(new[] {8,9});
Console.WriteLine($"Count: {numbers.Count}");
foreach(var num in numbers){
Console.Write($"{num} ");
}
}
}
```
而对于 `Dictionary<TKey,TValue>` :
```csharp
using System;
using System.Collections.Generic;
public class ExampleClass {
public static void Main(){
var capitals = new Dictionary<string,string>();
// 插入新的键值对
capitals.Add("France","Paris");
capitals["Italy"] = "Rome";
string capitalOfGermany = "";
bool hasCapital = capitals.TryGetValue("Germany", out capitalOfGermany);
if(!hasCapital){
Console.WriteLine("No entry found for Germany.");
}
foreach(KeyValuePair<string,string> kvp in capitals){
Console.WriteLine("{0}: {1}",kvp.Key,kvp.Value);
}
}
}
```
阅读全文
相关推荐


















