c#中用IComparable实现排序

本文介绍了一个使用C#语言实现的学生对象列表排序的例子。通过继承IComparable接口,学生类可以按照姓名或年龄进行排序。代码展示了如何创建学生对象、添加到列表中,并调用Sort方法来对列表进行排序。

static void Main(string[] args)
{
List st = new List();
Student s1 = new Student(“za”, 1);
Student s2 = new Student(“ha”, 4);
Student s3 = new Student(“la”, 5);
Student s4 = new Student(“ka”, 3);
st.Add(s1);
st.Add(s2);
st.Add(s3);
st.Add(s4);
st.Sort();
for (int i = 0; i < st.Count; i++)
{
Console.WriteLine(st[i]);
}
//这里我们的student要实现:IComparable并添加要排序的对象
class Student:IComparable
{
string _name;
int _age;

public string Name
    {
        get
        {
            return _name;
        }

        set
        {
            _name = value;
        }
    }

    public int Age
    {
        get
        {
            return _age;
        }

        set
        {
            _age = value;
        }
    }

    public Student(string name,int age)
    {
        this._name = name;
        this._age = age;
    }
    public override string ToString()
    {
        return this._name+" " +this._age;
    }

    public int CompareTo(Student other)
    {
    //根据年龄进行排序(根据姓名的首字母进行排序,若首字母相同,对下一个字母进行排序)
        //if (this.Age > other.Age)
        //{
        //    return 1;
        //}
        //else if (this.Age < other.Age)
        //{
        //    return -1;
        //}
        //else
        //{
        //    return 0;
        //}
        //根据姓名进行排序
       // int result = this._name.CompareTo(other.Name);
        //if (result == 0)
       // {
        //    result = this._name.CompareTo(other.Name);
       // }
       // return result;

    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值