日期:2014-05-17  浏览次数:21037 次

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();
        }
    }
}