• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
james1207

博客园    首页    新随笔    联系   管理    订阅  订阅

C#实现Comparable接口实现排序

C#中,实现排序的方法有两种,即实现Comparable或Comparer接口,下面简单介绍实现Comparable接口实现排序功能。

实现Comparable接口需要实现CompareTo(object obj)方法,所以简单实现这个方法就可以很方便的调用其排序功能。

以Student的score为例,进行排序:

具体代码:

 

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

namespace ConsoleApplicationtest
{
    class Program
    {
        public class Student:IComparable
        {
            int _socre;
            string _name;
            public int score
            {
                set { _socre = value; }
                get { return _socre; }
            }

            public string name
            {
                set { _name = value; }
                get { return _name; }
            }

            public void Display()
            {
                Console.WriteLine("姓名:{0}\t分数:{1}",_name,_socre);
            }

            public int CompareTo(object obj)//实现接口
            {
                Student stu = (Student)obj;
                return this._socre - stu._socre;
            }
        }
        static void Main(string[] args)
        {
            List<Student> stuList = new List<Student>();
            stuList.Add(new Student() { score = 98, name = "Bob" });
            stuList.Add(new Student() { score = 56, name = "Alice" });
            stuList.Add(new Student() { score = 100, name = "Jerry" });
            Console.WriteLine("排序前:");
            foreach (Student mystu in stuList)
            {
                mystu.Display();
            }
            stuList.Sort();
            Console.WriteLine("\n排序后:");
            foreach (Student mystu in stuList)
            {
                mystu.Display();
            }
            Console.ReadKey();
        }
    }
}


 


 

posted @ 2013-10-10 22:21  Class Xman  阅读(316)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3