C# SortedList 键值对排序。

本文通过一个具体的示例介绍了如何使用SortedList集合类存储不同类型的值,并展示了如何遍历这些值。具体包括了如何创建SortedList对象、添加各种类型的数据(如整数、自定义类的实例和字符串)作为值,以及如何输出排序后的键值对。
class tt
    {
        public int value;
        public override string ToString()
        {
            return value.ToString();
        }

    }


    SortedList ha = new SortedList();

            tt t1 = new tt();
            t1.value = 533;


            ha[5.5] = 56;
            ha[3.4] = t1;//可以赋值为类的对象
            ha[7.5] = "lili";
            ha[4.5] = "lili";
            ha[3.0] = "lili";

//输出结果是根据键的内容进行排序的,而且同一个对象键的类型只能为同一种,如只有int,只有double.或者只有string等,混用会报错 
            foreach (DictionaryEntry d in ha)
            {
                Console.WriteLine("{0}     {1}", d.Key, d.Value);
            }

### C# 中 `SortedList` 的排序机制 在 C# 中,`SortedList<TKey, TValue>` 是一种集合类型,它内部维护着按键排序的键/值对。当实例化 `SortedList` 时,默认情况下会按照键的自然顺序进行排序[^1]。 对于自定义类型的键,可以通过实现 `IComparer<T>` 接口来自定义比较逻辑,从而控制排序方式。下面是一个简单的例子展示如何向 `SortedList<int, string>` 添加元素并查看其自动排序效果: ```csharp using System; using System.Collections.Generic; class Program { static void Main() { // 创建一个新的 SortedList 实例 var sortedList = new SortedList<int, string>(); // 向其中添加一些数据项 sortedList.Add(3, "Three"); sortedList.Add(1, "One"); sortedList.Add(2, "Two"); foreach (var item in sortedList) { Console.WriteLine($"Key: {item.Key}, Value: {item.Value}"); } } } ``` 这段程序将会输出如下结果: ``` Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three ``` 这表明即使输入的数据不是有序的,`SortedList` 也会根据键值大小自动调整存储位置以维持整体序列的有序性[^2]。 另外,在某些场景下可能需要更复杂的排序规则,比如基于特定字段或属性来进行升序或降序排列。这时可以借助于实现了 `IComparer<T>` 接口的对象作为参数传递给 `SortedList` 构造函数来定制排序行为[^3]。 例如,如果要创建一个按字符串长度降序排列的 `SortedList<string, int>` 可以这样做: ```csharp public class StringLengthComparer : IComparer<string> { public int Compare(string x, string y) { return y.Length.CompareTo(x.Length); } } // 使用自定义比较器初始化 SortedList var lengthSortedDict = new SortedList<string, int>(new StringLengthComparer()); lengthSortedDict.Add("apple", 1); lengthSortedDict.Add("banana", 2); lengthSortedDict.Add("grapefruit", 3); foreach (var pair in lengthSortedDict) { Console.WriteLine($"{pair.Key}: {pair.Value}"); } ``` 上述代码片段展示了如何利用外部比较器对象改变默认排序策略,并且能够处理更加复杂的应用需求[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值