.Net编程接口剖析系列之比较和排序
我们来看看下面的代码,这里定义了一个学生类Student,每个学生有自己名字和分数。Student类实现了IComparable接口,两个学生之间直接按照名字进行比较。顺便说明Scores类用于存储学生的成绩。
public enum SubjectEnum
{
Total =0,
Chinese,
English,
Math,
}
public class Scores //分数类,用于存储分数
{
int[] _score = new int[4];
public int this[SubjectEnum score]
{
get { return _score[(int)score]; }
set { _score[(int)score] = value; }
}
public override string ToString()
{
string str = "";
foreach (int score in _score)
{
str += "\t" + score.ToString();
}
return str;
}
}
public class Student:IComparable //学生类
{
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
Scores _scores=new Scores();
public Scores Scores
{
get { return _scores; }
set { _scores = value; }
}
public Student(string name,int chinese, int english, int math)
{
_name = name;
_scores[SubjectEnum.Chinese] = chinese;
_scores[SubjectEnum.English] = english;
_scores[SubjectEnum.Math] = math;
_scores[SubjectEnum.Total] = chinese +english +math;
}
public override string ToString()
{
return _name + _scores.ToString();
}
#region IComparable Members
public int CompareTo(object obj)
{
if (!(obj is Student))
throw new ArgumentException("Argument not a Student", "obj");
return Name.CompareTo(((Student)obj).Name);
}
#endregion
}
来看看我们的Main函数,我们在一个数组中存储了若干个学生,并且利用了Array.Sort对起进行了排序。
static void Main(string[] args)
{
Student[] students = new Student[4];
students[0] = new Student("Michale", 80, 90, 70);
students[1] = new Student("Jack", 90, 80, 75);
students[2] = new Student("Alex", 88, 85, 95);
students[3] = new Student("Rose", 92, 91, 65);
Array.Sort(students);
Console.WriteLine("Name\tTotal\tChinese\tEnglish\tMath");
foreach (Student student in students)
{
Console.WriteLine(student);
}
Console.ReadKey();
}
下面来看看输出结果:
| Name | Total | Chinese | English | Math |
| Alex | 268 | 88 | 85 | 95 |
| Jack | 245 | 90 | 80 | 75 |
| Michale | 240 | 80 | 90 | 70 |
| Rose | 248 | 92 | 91 | 65 |
可以发现,学生们被很好的按照名称字母的顺序进行了排序,并且从小到大地打印出来了。但是我们这里还是要留下一个问题,假如我们有时候需要按照某项成绩进行排序又如何实现呢?假如我们排序的时候希望按照降序进行排列又该如何呢?呵呵,聪明的读者可能已经想到了,这正是我下一节想要说的内容。
0
相关文章