集合概述 #

一、集合体系结构 #

1.1 核心接口 #

text
IEnumerable
    ↓
ICollection
    ├── IList
    │   ├── List<T>
    │   └── Array
    └── IDictionary
        ├── Dictionary<K,V>
        └── SortedDictionary<K,V>

ISet
    ├── HashSet<T>
    └── SortedSet<T>

1.2 接口说明 #

接口 说明
IEnumerable 可枚举,支持foreach
ICollection 集合基接口
IList 有序集合,支持索引访问
IDictionary 键值对集合
ISet 不重复元素集合

二、IEnumerable接口 #

2.1 基本用法 #

csharp
public interface IEnumerable
{
    IEnumerator GetEnumerator();
}

public interface IEnumerable<out T> : IEnumerable
{
    IEnumerator<T> GetEnumerator();
}

2.2 实现IEnumerable #

csharp
public class NumberRange : IEnumerable<int>
{
    private readonly int _start;
    private readonly int _end;
    
    public NumberRange(int start, int end)
    {
        _start = start;
        _end = end;
    }
    
    public IEnumerator<int> GetEnumerator()
    {
        for (int i = _start; i <= _end; i++)
        {
            yield return i;
        }
    }
    
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

foreach (var n in new NumberRange(1, 5))
{
    Console.WriteLine(n);
}

2.3 yield关键字 #

csharp
public static IEnumerable<int> GetEvenNumbers(int max)
{
    for (int i = 0; i <= max; i += 2)
    {
        yield return i;
    }
}

public static IEnumerable<int> FilterPositive(IEnumerable<int> numbers)
{
    foreach (var n in numbers)
    {
        if (n > 0)
            yield return n;
    }
}

三、ICollection接口 #

3.1 接口成员 #

csharp
public interface ICollection<T> : IEnumerable<T>
{
    int Count { get; }
    bool IsReadOnly { get; }
    void Add(T item);
    void Clear();
    bool Contains(T item);
    void CopyTo(T[] array, int arrayIndex);
    bool Remove(T item);
}

3.2 使用示例 #

csharp
ICollection<string> names = new List<string> { "张三", "李四" };

Console.WriteLine($"数量:{names.Count}");
Console.WriteLine($"只读:{names.IsReadOnly}");

names.Add("王五");
bool contains = names.Contains("张三");
bool removed = names.Remove("李四");
names.Clear();

四、IList接口 #

4.1 接口成员 #

csharp
public interface IList<T> : ICollection<T>
{
    T this[int index] { get; set; }
    int IndexOf(T item);
    void Insert(int index, T item);
    void RemoveAt(int index);
}

4.2 使用示例 #

csharp
IList<string> names = new List<string> { "张三", "李四", "王五" };

string first = names[0];
names[1] = "赵六";

int index = names.IndexOf("王五");
names.Insert(0, "钱七");
names.RemoveAt(2);

五、IDictionary接口 #

5.1 接口成员 #

csharp
public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>
{
    TValue this[TKey key] { get; set; }
    ICollection<TKey> Keys { get; }
    ICollection<TValue> Values { get; }
    void Add(TKey key, TValue value);
    bool ContainsKey(TKey key);
    bool Remove(TKey key);
    bool TryGetValue(TKey key, out TValue value);
}

5.2 使用示例 #

csharp
IDictionary<string, int> scores = new Dictionary<string, int>();

scores["张三"] = 85;
scores.Add("李四", 92);

int score = scores["张三"];
bool exists = scores.ContainsKey("王五");

if (scores.TryGetValue("李四", out int liScore))
{
    Console.WriteLine($"李四的分数:{liScore}");
}

foreach (var key in scores.Keys)
{
    Console.WriteLine($"{key}: {scores[key]}");
}

六、ISet接口 #

6.1 接口成员 #

csharp
public interface ISet<T> : ICollection<T>
{
    bool Add(T item);
    void ExceptWith(IEnumerable<T> other);
    void IntersectWith(IEnumerable<T> other);
    bool IsSubsetOf(IEnumerable<T> other);
    bool IsSupersetOf(IEnumerable<T> other);
    bool Overlaps(IEnumerable<T> other);
    bool SetEquals(IEnumerable<T> other);
    void SymmetricExceptWith(IEnumerable<T> other);
    void UnionWith(IEnumerable<T> other);
}

6.2 使用示例 #

csharp
ISet<int> set1 = new HashSet<int> { 1, 2, 3, 4, 5 };
ISet<int> set2 = new HashSet<int> { 4, 5, 6, 7, 8 };

set1.UnionWith(set2);
set1.IntersectWith(set2);
set1.ExceptWith(set2);

bool isSubset = set1.IsSubsetOf(set2);
bool overlaps = set1.Overlaps(set2);

七、集合选择指南 #

7.1 按需求选择 #

需求 推荐集合
有序、索引访问 List
频繁插入删除 LinkedList
不重复元素 HashSet
有序不重复 SortedSet
键值对 Dictionary<K,V>
有序键值对 SortedDictionary<K,V>
先进先出 Queue
后进先出 Stack

7.2 性能对比 #

操作 List HashSet Dictionary
查找 O(n) O(1) O(1)
添加 O(1) O(1) O(1)
删除 O(n) O(1) O(1)
索引访问 O(1) - -

八、集合初始化 #

8.1 集合初始化器 #

csharp
var list = new List<int> { 1, 2, 3, 4, 5 };
var dict = new Dictionary<string, int>
{
    ["张三"] = 85,
    ["李四"] = 92
};
var set = new HashSet<int> { 1, 2, 3 };

8.2 集合表达式(C# 12+) #

csharp
List<int> list = [1, 2, 3, 4, 5];
int[] array = [1, 2, 3];
HashSet<int> set = [1, 2, 3];

List<int> CreateList(int a, int b) => [a, b];

九、只读集合 #

9.1 IReadOnlyCollection #

csharp
public IReadOnlyList<int> GetNumbers()
{
    return new List<int> { 1, 2, 3 }.AsReadOnly();
}

public IReadOnlyDictionary<string, int> GetScores()
{
    return new Dictionary<string, int>
    {
        ["张三"] = 85
    };
}

9.2 不可变集合 #

csharp
using System.Collections.Immutable;

var list = ImmutableList.Create(1, 2, 3);
var newList = list.Add(4);

var dict = ImmutableDictionary.CreateBuilder<string, int>();
dict.Add("张三", 85);
var immutableDict = dict.ToImmutable();

十、总结 #

集合体系要点:

接口 说明
IEnumerable 可枚举
ICollection 集合基接口
IList 有序集合
IDictionary 键值对
ISet 不重复集合

下一步,让我们学习List集合!

最后更新:2026-03-26