Set集合 #

一、Set集合概述 #

Set集合存储不重复的元素,支持集合运算。

1.1 特点 #

  • 元素唯一
  • 高效查找
  • 支持集合运算

1.2 类型对比 #

类型 特点
HashSet 无序,高性能
SortedSet 有序,红黑树实现

二、HashSet #

2.1 创建HashSet #

csharp
var set1 = new HashSet<int>();
var set2 = new HashSet<int> { 1, 2, 3, 4, 5 };
var set3 = new HashSet<int>(new[] { 1, 2, 2, 3, 3, 3 });

2.2 添加元素 #

csharp
var set = new HashSet<string>();

bool added1 = set.Add("张三");
bool added2 = set.Add("张三");

2.3 删除元素 #

csharp
var set = new HashSet<int> { 1, 2, 3, 4, 5 };

bool removed = set.Remove(3);
int count = set.RemoveWhere(n => n > 3);
set.Clear();

2.4 查找元素 #

csharp
var set = new HashSet<int> { 1, 2, 3, 4, 5 };

bool contains = set.Contains(3);
int count = set.Count;

2.5 遍历 #

csharp
var set = new HashSet<string> { "张三", "李四", "王五" };

foreach (var item in set)
{
    Console.WriteLine(item);
}

三、集合运算 #

3.1 并集 #

csharp
var set1 = new HashSet<int> { 1, 2, 3 };
var set2 = new HashSet<int> { 3, 4, 5 };

set1.UnionWith(set2);

var union = new HashSet<int>(set1);
union.UnionWith(set2);

3.2 交集 #

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

set1.IntersectWith(set2);

var intersection = set1.Intersect(set2).ToHashSet();

3.3 差集 #

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

set1.ExceptWith(set2);

var except = set1.Except(set2).ToHashSet();

3.4 对称差集 #

csharp
var set1 = new HashSet<int> { 1, 2, 3 };
var set2 = new HashSet<int> { 3, 4, 5 };

set1.SymmetricExceptWith(set2);

3.5 子集判断 #

csharp
var set1 = new HashSet<int> { 1, 2 };
var set2 = new HashSet<int> { 1, 2, 3, 4, 5 };

bool isSubset = set1.IsSubsetOf(set2);
bool isProperSubset = set1.IsProperSubsetOf(set2);
bool isSuperset = set2.IsSupersetOf(set1);
bool isProperSuperset = set2.IsProperSupersetOf(set1);

3.6 重叠判断 #

csharp
var set1 = new HashSet<int> { 1, 2, 3 };
var set2 = new HashSet<int> { 3, 4, 5 };

bool overlaps = set1.Overlaps(set2);
bool equals = set1.SetEquals(set2);

四、SortedSet #

4.1 创建SortedSet #

csharp
var set1 = new SortedSet<int>();
var set2 = new SortedSet<int> { 5, 2, 8, 1, 9 };
var set3 = new SortedSet<int>(Comparer<int>.Create((a, b) => b.CompareTo(a)));

4.2 有序特性 #

csharp
var set = new SortedSet<int> { 5, 2, 8, 1, 9 };

foreach (var item in set)
{
    Console.WriteLine(item);
}

4.3 范围操作 #

csharp
var set = new SortedSet<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var view = set.GetViewBetween(3, 7);

int min = set.Min;
int max = set.Max;

4.4 自定义排序 #

csharp
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

var people = new SortedSet<Person>(Comparer<Person>.Create((a, b) => 
{
    int result = a.Age.CompareTo(b.Age);
    return result != 0 ? result : string.Compare(a.Name, b.Name);
}));

people.Add(new Person { Name = "张三", Age = 25 });
people.Add(new Person { Name = "李四", Age = 20 });
people.Add(new Person { Name = "王五", Age = 30 });

五、实战示例 #

5.1 去重 #

csharp
public static List<T> RemoveDuplicates<T>(List<T> list)
{
    return new HashSet<T>(list).ToList();
}

public static List<T> RemoveDuplicates<T>(List<T> list, IEqualityComparer<T> comparer)
{
    return new HashSet<T>(list, comparer).ToList();
}

5.2 标签系统 #

csharp
public class Article
{
    public int Id { get; set; }
    public string Title { get; set; }
    public HashSet<string> Tags { get; set; } = new();
}

var article1 = new Article { Id = 1, Title = "C#教程" };
article1.Tags.Add("C#");
article1.Tags.Add("编程");
article1.Tags.Add("教程");

var article2 = new Article { Id = 2, Title = "Java教程" };
article2.Tags.Add("Java");
article2.Tags.Add("编程");
article2.Tags.Add("教程");

var commonTags = new HashSet<string>(article1.Tags);
commonTags.IntersectWith(article2.Tags);
Console.WriteLine($"共同标签:{string.Join(", ", commonTags)}");

5.3 权限管理 #

csharp
[Flags]
public enum Permission
{
    None = 0,
    Read = 1,
    Write = 2,
    Delete = 4,
    Admin = 8
}

public class User
{
    public string Name { get; set; }
    public HashSet<Permission> Permissions { get; } = new();
    
    public bool HasPermission(Permission permission)
    {
        return Permissions.Contains(permission) || Permissions.Contains(Permission.Admin);
    }
    
    public void Grant(Permission permission) => Permissions.Add(permission);
    public void Revoke(Permission permission) => Permissions.Remove(permission);
}

5.4 唯一ID生成器 #

csharp
public class UniqueIdGenerator
{
    private readonly HashSet<int> _usedIds = new();
    private readonly Random _random = new();
    
    public int Generate()
    {
        int id;
        do
        {
            id = _random.Next(1, int.MaxValue);
        } while (!_usedIds.Add(id));
        return id;
    }
    
    public bool Release(int id) => _usedIds.Remove(id);
    
    public bool IsUsed(int id) => _usedIds.Contains(id);
}

六、性能比较 #

6.1 查找性能 #

csharp
var list = Enumerable.Range(0, 100000).ToList();
var set = new HashSet<int>(list);

var sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
    list.Contains(50000);
}
sw.Stop();
Console.WriteLine($"List: {sw.ElapsedMilliseconds}ms");

sw.Restart();
for (int i = 0; i < 10000; i++)
{
    set.Contains(50000);
}
sw.Stop();
Console.WriteLine($"HashSet: {sw.ElapsedMilliseconds}ms");

6.2 选择建议 #

场景 推荐
需要去重 HashSet
需要有序 SortedSet
频繁查找 HashSet
范围查询 SortedSet

七、总结 #

Set集合要点:

操作 HashSet SortedSet
添加 Add Add
删除 Remove Remove
查找 Contains Contains
并集 UnionWith UnionWith
交集 IntersectWith IntersectWith
差集 ExceptWith ExceptWith

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

最后更新:2026-03-26