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