在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