根据集合中某元素(对象)的某个属性,给整个集合中的元素进行排序
学生类中有名字,年龄,成绩三个属性。将类实例化为对象之后,如果根据 每个对象中的成绩属性 给集合中的元素按成绩从高到低的排列?
下面是我写的代码,功能可以实现,但算法很低效,求更高效的算法!!!
主窗体:
public partial class Form1 : Form
{
School Scs;
Student[] StusArr;//将集合中的元素放入对象数组 方便排序
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Scs = new School();
Scs.Stus.Add(new Student() { name = "张林", age = 16, Result = 92 });
Scs.Stus.Add(new Student() { name = "刘允", age = 12, Result = 85 });
Scs.Stus.Add(new Student() {name="李熊涛",age=17,Result=98 });
Scs.Stus.Add(new Student() { name = "龚祥", age = 19,Result=87 });
Scs.Stus.Add(new Student() { name = "王翰", age = 20, Result = 91 });
Scs.Stus.Add(new Student() { name = "陈豪", age = 26, Result = 99 });
StusArr=new Student[Scs.Stus.Count];//对象数据的长度
int j = 0;
foreach (Student stu in Scs.Stus)
{
StusArr[j] = stu;
j++;
}
for (int a = 0; a < Scs.Stus.Count;a++ )
{
for (int b = 0; b < Scs.Stus.Count-1-a; b++)
{
if (StusArr[b].Result < StusArr[b + 1].Result)
{
Student stu;
stu = StusArr[b];
StusArr[b] = StusArr[b + 1];
StusArr[b + 1] = stu;
}
}
}
foreach(Student stu in StusArr)
{
MessageBox.Show(String.Format("name: {0} age: {1} result: {2}",stu.name,stu.age,stu.Result));
}
}
}
学校类(用于存学生集合):
class School
{
public List<Student> Stus { get; set; }//学生集合
public School()
{
Stus = new List<Student>();
}
}
学生类:
class Student
{
public string name { get; set; }
public int age { get; set; }
public int Result { get; set; }
}
我是通过foreach把集合中的元素放到对象数组中,然后通过冒泡排序对元素进行排序,功能可以实现,但效率忒低了
求大神指导!!!
[解决办法]
http://www.cnblogs.com/luminji/archive/2010/09/30/1839038.html