使用C#完成Windows程序作业2:对象集合如何排序1、 题目说明:学生类包括成绩、科目和学号,请根据课程成绩grade将学生进行排序。2、 部分代码如下,请将代码补充完整public class Student : IComparable{ public double mygrade; public string mysubject, myID; public Student() { } public Student(double grade, string subject, string id) { mygrade = grade; mysubject = subject; myID = id; } 请在此处添加关键代码···}internal class Program{ private static void Main(string[] args) { Student[] students = new Student[5]; students[0] = new Student(50.0, "windows程序设计", "001"); students[1] = new Student(90.0, "windows程序设计", "002"); students[2] = new Student(100.0, "windows程序设计", "003"); students[3] = new Student(70.0, "windows程序设计", "004"); students[4] = new Student(80.0, "windows程序设计", "005"); 请在此处添加关键代码··· }}
public class Student : IComparable<Student>
{
public double mygrade;
public string mysubject, myID;
public Student() { }
public Student(double grade, string subject, string id)
{
mygrade = grade;
mysubject = subject;
myID = id;
}
public int CompareTo(Student other)
{
if (other == null) return 1;
return mygrade.CompareTo(other.mygrade);
}
}
internal class Program
{
private static void Main(string[] args)
{
Student[] students = new Student[5];
students[0] = new Student(50.0, "windows程序设计", "001");
students[1] = new Student(90.0, "windows程序设计", "002");
students[2] = new Student(100.0, "windows程序设计", "003");
students[3] = new Student(70.0, "windows程序设计", "004");
students[4] = new Student(80.0, "windows程序设计", "005");
Array.Sort(students);
foreach (Student s in students)
{
Console.WriteLine("Grade: {0}, Subject: {1}, ID: {2}", s.mygrade, s.mysubject, s.myID);
}
Console.ReadLine();
}
}
在上面的解决方案中,Student 类实现了 IComparable<Student> 接口,指定了使用 CompareTo 方法进行排序。在 CompareTo 方法中,我们按照 mygrade 属性进行比较。Array.Sort 方法可用于按照 CompareTo 方法的结果对数组中的对象进行排序。
最后,在 Main 方法中创建 Student 对象数组,并调用 Array.Sort 方法对其进行排序。将结果输出到控制台。