是的,C# 中的 HashSet<T>
集合不支持排序。HashSet<T>
是一個無序的集合,它不允許重復元素,并且不保證元素的順序。
如果你需要對集合中的元素進行排序,可以使用 List<T>
或 SortedSet<T>
集合。List<T>
是一個有序的集合,你可以使用 List<T>.Sort()
方法對集合中的元素進行排序。SortedSet<T>
是一個有序的集合,它會自動對元素進行排序,你不需要手動進行排序操作。
以下是一個示例,展示了如何使用 List<T>
對集合中的元素進行排序:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 創建一個包含整數的 HashSet
HashSet<int> hashSet = new HashSet<int> { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 };
// 將 HashSet 轉換為 List
List<int> list = new List<int>(hashSet);
// 對 List 進行排序
list.Sort();
// 輸出排序后的 List
Console.WriteLine("Sorted List:");
foreach (int item in list)
{
Console.WriteLine(item);
}
}
}
輸出結果:
Sorted List:
1
1
2
3
3
4
5
5
5
6
9