在C#中,您可以使用SortedSet<KeyValuePair<TKey, TValue>>或SortedSet<T>來存儲鍵值對并自動對其進行排序。SortedSet是基于紅黑樹實現的,它會根據鍵或值的自然順序或者提供的比較器進行排序。
以下是一個使用SortedSet<KeyValuePair<TKey, TValue>>的示例:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 創建一個包含鍵值對的列表
List<KeyValuePair<int, string>> keyValuePairs = new List<KeyValuePair<int, string>>
{
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two")
};
// 使用SortedSet存儲鍵值對并自動排序
SortedSet<KeyValuePair<int, string>> sortedSet = new SortedSet<KeyValuePair<int, string>>(keyValuePairs);
// 輸出排序后的鍵值對
foreach (var item in sortedSet)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
}
}
如果您想根據值進行排序,可以使用SortedSet<T>并實現一個自定義比較器:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 創建一個包含鍵值對的列表
List<KeyValuePair<int, string>> keyValuePairs = new List<KeyValuePair<int, string>>
{
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two")
};
// 使用SortedSet存儲鍵值對并自動根據值排序
SortedSet<KeyValuePair<int, string>> sortedSet = new SortedSet<KeyValuePair<int, string>>(
keyValuePairs,
new Comparer<KeyValuePair<int, string>>(
(x, y) => string.Compare(x.Value, y.Value)
)
);
// 輸出排序后的鍵值對
foreach (var item in sortedSet)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
}
}
這兩個示例都會輸出按值排序的鍵值對:
Key: 1, Value: one
Key: 2, Value: two
Key: 3, Value: three