C#中SortedSet的具體使用
基礎(chǔ)概念
SortedSet 是 C# 中的一個(gè)集合類型,位于 System.Collections.Generic 命名空間下。它是一個(gè)自動(dòng)排序的集合,用于存儲不重復(fù)的元素,并且會根據(jù)元素的自然順序(默認(rèn)排序)或自定義比較器進(jìn)行排序,內(nèi)部使用紅黑樹數(shù)據(jù)結(jié)構(gòu)來維護(hù)元素的有序性。
- 自動(dòng)排序:每次添加或刪除元素時(shí),SortedSet 都會自動(dòng)調(diào)整以保持元素的排序狀態(tài)。
- 不重復(fù)元素:SortedSet 不允許重復(fù)的元素。如果嘗試添加一個(gè)已經(jīng)存在的元素,該操作會被忽略。
- 高效性:SortedSet 內(nèi)部使用紅黑樹(一種自平衡二叉搜索樹)實(shí)現(xiàn),因此查找、插入和刪除操作的時(shí)間復(fù)雜度為 O(log n)。
主要特性
- 自動(dòng)保持元素排序:元素會根據(jù)其自然順序(需實(shí)現(xiàn) IComparable<T> 接口)或自定義比較器(IComparer<T>)排序。
- 不包含重復(fù)元素:嘗試添加已有元素時(shí),Add 方法返回 false,集合保持不變。
- 支持集合操作:提供并集、交集、差集等操作。
- 支持子集視圖:可以通過方法獲取某個(gè)范圍內(nèi)的元素。
- 快速訪問邊界值:提供 Min 和 Max 屬性,快速獲取最小和最大元素。
創(chuàng)建和初始化
基本創(chuàng)建方式
使用默認(rèn)比較器(升序)
// 使用默認(rèn)比較器(升序) SortedSet<int> numbers = new SortedSet<int>();
使用自定義比較器
// 使用自定義比較器 SortedSet<string> names = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
從現(xiàn)有集合創(chuàng)建
// 從現(xiàn)有集合創(chuàng)建
int[] array = { 5, 2, 8, 1, 9 };
SortedSet<int> sortedNumbers = new SortedSet<int>(array);
// 結(jié)果:{1, 2, 5, 8, 9}使用集合初始化器
// 使用集合初始化器
SortedSet<string> fruits = new SortedSet<string> { "Apple", "Banana", "Cherry" };自定義比較器
降序排列
// 降序排列 SortedSet<int> descendingNumbers = new SortedSet<int>(Comparer<int>.Create((x, y) => y.CompareTo(x)));
自定義對象排序
// 自定義對象排序
public class Person : IComparable<Person>
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Person other)
{
if (other == null) return 1;
return this.Age.CompareTo(other.Age); // 按年齡排序
}
}
SortedSet<Person> people = new SortedSet<Person>();使用自定義比較器
// 或使用自定義比較器
SortedSet<Person> peopleByName = new SortedSet<Person>(
Comparer<Person>.Create((p1, p2) => string.Compare(p1.Name, p2.Name))
);基本操作
添加和刪除元素
SortedSet<int> numbers = new SortedSet<int>();
添加元素
// 添加元素
bool added1 = numbers.Add(5); // true,成功添加
bool added2 = numbers.Add(3); // true,成功添加
bool added3 = numbers.Add(5); // false,元素已存在
Console.WriteLine(string.Join(", ", numbers)); // 輸出:3, 5刪除元素
// 刪除元素 bool removed = numbers.Remove(3); // true,成功刪除 numbers.Remove(10);
清空集合
// 清空集合 numbers.Clear();
查詢操作
SortedSet<int> numbers = new SortedSet<int> { 1, 3, 5, 7, 9 };檢查元素是否存在
// 檢查元素是否存在 bool contains = numbers.Contains(5); // true
獲取元素?cái)?shù)量
// 獲取元素?cái)?shù)量 int count = numbers.Count; // 5
檢查是否為空
// 檢查是否為空 bool isEmpty = numbers.Count == 0; // false
獲取最小值和最大值
// 獲取最小值和最大值 int min = numbers.Min; // 1 int max = numbers.Max; // 9
范圍查詢
使用 GetViewBetween 方法獲取指定范圍內(nèi)的元素子集
SortedSet<int> numbers = new SortedSet<int> { 1, 3, 5, 7, 9, 11, 13 };
// 獲取視圖(不創(chuàng)建新集合)
SortedSet<int> subset1 = numbers.GetViewBetween(3, 9);
// 結(jié)果:{3, 5, 7, 9}
SortedSet<int> subset2 = numbers.GetViewBetween(4, 10);
// 結(jié)果:{5, 7, 9}
// 視圖會反映原集合的變化
numbers.Add(6);
Console.WriteLine(string.Join(", ", subset2)); // 輸出:5, 6, 7, 9集合運(yùn)算
并集、交集、差集
SortedSet<int> set1 = new SortedSet<int> { 1, 2, 3, 4, 5 };
SortedSet<int> set2 = new SortedSet<int> { 4, 5, 6, 7, 8 };并集:UnionWith 將另一個(gè)集合的元素合并到 SortedSet 中。
// 并集(修改 set1)
set1.UnionWith(set2);
Console.WriteLine(string.Join(", ", set1)); // 1, 2, 3, 4, 5, 6, 7, 8交集:IntersectWith 保留與另一個(gè)集合的交集。
// 重新初始化
set1 = new SortedSet<int> { 1, 2, 3, 4, 5 };
// 交集(修改 set1)
set1.IntersectWith(set2);
Console.WriteLine(string.Join(", ", set1)); // 4, 5差集:ExceptWith 刪除與另一個(gè)集合相交的元素。
// 重新初始化
set1 = new SortedSet<int> { 1, 2, 3, 4, 5 };
// 差集(set1 中有但 set2 中沒有的元素)
set1.ExceptWith(set2);
Console.WriteLine(string.Join(", ", set1)); // 1, 2, 3對稱差集:SymmetricExceptWith 兩個(gè)集合中不共同擁有的元素
// 對稱差集(兩個(gè)集合中不共同擁有的元素)
set1 = new SortedSet<int> { 1, 2, 3, 4, 5 };
set1.SymmetricExceptWith(set2);
Console.WriteLine(string.Join(", ", set1)); // 1, 2, 3, 6, 7, 8集合關(guān)系判斷
SortedSet<int> set1 = new SortedSet<int> { 1, 2, 3 };
SortedSet<int> set2 = new SortedSet<int> { 1, 2, 3, 4, 5 };
SortedSet<int> set3 = new SortedSet<int> { 2, 3 };
SortedSet<int> set4 = new SortedSet<int> { 6, 7 };子集判斷
// 子集判斷 bool isSubset = set1.IsSubsetOf(set2); // true bool isProperSubset = set1.IsProperSubsetOf(set2); // true bool isSuperset = set2.IsSupersetOf(set1); // true bool isProperSuperset = set2.IsProperSupersetOf(set1); // true
重疊判斷
// 重疊判斷 bool overlaps = set1.Overlaps(set3); // true(有共同元素2,3) bool overlaps2 = set1.Overlaps(set4); // false(無共同元素)
相等判斷
// 相等判斷 bool areEqual = set1.SetEquals(set3); // false
遍歷和枚舉
基本遍歷
SortedSet<string> fruits = new SortedSet<string> { "Banana", "Apple", "Cherry" };foreach 遍歷(按排序順序)
// foreach 遍歷(按排序順序)
foreach (string fruit in fruits)
{
Console.WriteLine(fruit); // Apple, Banana, Cherry
}使用枚舉器
// 使用枚舉器
using (var enumerator = fruits.GetEnumerator())
{
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
}反向遍歷
SortedSet<int> numbers = new SortedSet<int> { 1, 3, 5, 7, 9 };
// 反向遍歷
foreach (int number in numbers.Reverse())
{
Console.WriteLine(number); // 9, 7, 5, 3, 1
}SortedSet 的優(yōu)點(diǎn)和適用場景
優(yōu)點(diǎn)
- 自動(dòng)保持元素排序,無需手動(dòng)干預(yù)。
- 確保元素唯一性,避免重復(fù)。
- 高效的操作性能(O(log n))。
- 支持集合操作和子集視圖。
適用場景
- 需要有序且不重復(fù)的元素集合,例如排行榜、時(shí)間線。
- 實(shí)現(xiàn)優(yōu)先級隊(duì)列(盡管 C# 有 PriorityQueue<T>)。
- 執(zhí)行集合操作,如并集、交集等。
SortedSet 與其他集合類型的區(qū)別
- 與 HashSet<T> 的區(qū)別:
- HashSet<T> 不保持順序,查找時(shí)間為 O(1)。
- SortedSet<T> 保持順序,查找時(shí)間為 O(log n)。
- 與 List<T> 的區(qū)別:
- List<T> 允許重復(fù)元素,不自動(dòng)排序。
- SortedSet<T> 不允許重復(fù),自動(dòng)排序。
- 與 SortedList<TKey, TValue> 的區(qū)別:
- SortedList<TKey, TValue> 是鍵值對集合,鍵排序。
- SortedSet<T> 是元素集合,元素本身排序。
到此這篇關(guān)于C#中SortedSet的具體使用的文章就介紹到這了,更多相關(guān)C# SortedSet內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#調(diào)用C++ DLL bool返回值始終為true的問題
這篇文章主要介紹了C#調(diào)用C++ DLL bool返回值始終為true的問題及解決,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
C#中多維數(shù)組[,]和交錯(cuò)數(shù)組[][]的區(qū)別
這篇文章介紹了C#中多維數(shù)組[,]和交錯(cuò)數(shù)組[][]的區(qū)別,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01
C#/VB.NET 給Excel添加、刪除數(shù)字簽名的方法
這篇文章主要介紹了C#/VB.NET 給Excel添加、刪除數(shù)字簽名的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
C#實(shí)現(xiàn)可捕獲幾乎所有鍵盤鼠標(biāo)事件的鉤子類完整實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)可捕獲幾乎所有鍵盤鼠標(biāo)事件的鉤子類,以完整實(shí)例形式分析了C#捕獲鍵盤鼠標(biāo)事件的鉤子操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06
C#觀察者模式(Observer Pattern)實(shí)例教程
這篇文章主要介紹了C#觀察者模式(Observer Pattern),主要以一個(gè)實(shí)例的形式講述了C#觀察者模式的實(shí)現(xiàn)過程,詳細(xì)講述了接口的定義、通知及動(dòng)作的實(shí)現(xiàn)方法,需要的朋友可以參考下2014-09-09
使用C#實(shí)現(xiàn)插入各種表格到Word文檔
在許多企業(yè)應(yīng)用場景中,Word 文檔依舊是最常用的信息呈現(xiàn)與內(nèi)容輸出格式,下面將介紹在 C# 中如何以編程方式創(chuàng)建 Word 文檔、插入表格、設(shè)置樣式,并擴(kuò)展到動(dòng)態(tài)行列與嵌套表格等高級操作,希望對大家有所幫助2025-11-11

