在 C# 编程中,处理集合数据是日常开发的重要部分。如果你需要一个既能自动排序又能确保元素不重复的集合类型,那么 SortedSet<T> 就是你理想的选择!本文将从零开始,带你全面了解 C# 中的 SortedSet<T>,即使是编程小白也能轻松上手。

SortedSet<T> 是 .NET Framework 提供的一个泛型集合类,它实现了 ISet<T> 接口。它的两个核心特性是:
因此,SortedSet<T> 非常适合用于需要去重并保持有序的数据场景,比如排行榜、唯一日志记录、字典索引等。
首先,你需要引入命名空间 System.Collections.Generic。下面是一个简单的示例:
using System;using System.Collections.Generic;class Program{ static void Main() { // 创建一个 SortedSet SortedSet<int> numbers = new SortedSet<int>(); // 添加元素 numbers.Add(5); numbers.Add(1); numbers.Add(3); numbers.Add(5); // 重复,不会被添加 // 输出结果:1, 3, 5 foreach (int num in numbers) { Console.Write(num + " "); } }} 运行上述代码,你会看到输出为:1 3 5。注意,即使我们尝试添加两次数字 5,集合中也只保留了一个,并且所有元素自动按升序排列。
SortedSet<T> 提供了丰富的方法来操作集合:
Add(T item):添加元素,若已存在则返回 false。Remove(T item):移除指定元素。Contains(T item):检查是否包含某元素。Min / Max:获取最小值和最大值(O(1) 时间复杂度!)。Reverse():反向遍历集合。例如,快速获取最大最小值:
SortedSet<string> words = new SortedSet<string> { "banana", "apple", "cherry" };Console.WriteLine($"最小: {words.Min}, 最大: {words.Max}");// 输出:最小: apple, 最大: cherry默认情况下,SortedSet<T> 使用元素的自然顺序(如数字大小、字符串字母顺序)。但你也可以通过传入 IComparer<T> 来实现自定义排序。
例如,按字符串长度降序排列:
public class LengthComparer : IComparer<string>{ public int Compare(string x, string y) { // 按长度降序,长度相同时按字母升序 int lengthComparison = y.Length.CompareTo(x.Length); return lengthComparison != 0 ? lengthComparison : x.CompareTo(y); }}// 使用自定义比较器var set = new SortedSet<string>(new LengthComparer()){ "cat", "elephant", "dog", "bee"};foreach (var word in set){ Console.WriteLine(word);}// 输出:// elephant// bee// cat// dogSortedSet<T> 基于红黑树实现,因此插入、删除、查找操作的时间复杂度均为 O(log n)。相比 List<T> 手动排序,它在频繁增删且需保持有序的场景下效率更高。
典型应用场景包括:
通过本教程,你应该已经掌握了 C# 中 SortedSet<T> 的基本用法、核心特性和适用场景。记住,当你需要一个有序且无重复的集合时,SortedSet<T> 是一个强大而高效的工具。
希望这篇关于 C# SortedSet、有序集合、无重复集合 和 C#数据结构 的入门教程对你有所帮助!快去试试吧!
本文由主机测评网于2025-12-19发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025129809.html