.Net4.0 之排序列表

本文通过一个具体的示例介绍了如何使用C#中的SortedSet类来实现元素的自动排序功能,并展示了如何自定义排序规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天第一次尝试了一个SortedSet的排序列表,该列表可以实现插入元素的自动排序(排序规则需要自己指定)

写了个小例子:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    public class Sort
    {
        public void Begin()
        {
            //新建排序对象,构造函数中指定排序的方法实例
            SortedSet<Person> sortset = new SortedSet<Person>(new PersonSort());
            sortset.Add(new Person { name = "wangjue", age = 11 });
            sortset.Add(new Person { name = "wangjue4", age = 44 });
            sortset.Add(new Person { name = "wangjue3", age = 33 });
            sortset.Add(new Person { name = "wangjue2", age = 22 });

            foreach (var item in sortset)
            {
                Console.WriteLine(string.Format("the name is {0}, age is:{1}", item.name, item.age));
                //the name is wangjue, age is:11
                //the name is wangjue2, age is:22
                //the name is wangjue3, age is:33
                //the name is wangjue4, age is:44
            }
        }
    }

    /// <summary>
    /// 比较类,需要实现IComparer接口中的Compare方法。
    /// </summary>
    public class PersonSort : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            if (x.age > y.age)// x>y返回正数
            {
                return 1;
            }
            else
                if (x.age < y.age)
                {
                    return -1;
                }
                else
                {
                    return 0;
                }
        }
    }

    public class Person
    {
        public string name;
        public int age;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值