您的位置:首页 > 其它

通过委托实现灵活排序

2016-06-11 11:53 381 查看
我们在实际的编程中我们,常用的一些排序方法并不能满足我们的需求。比如,有时候我们需要给兔子的身高去排队,有时候我们需要去给青蛙的身高去排队,但是对于蛇,我们只能去比较蛇的身长。,对每一种动物去比较的时候,都去写一个比较方法有很多冗余。如果我们利用委托去实现一些方法器的实现,是不是比较好一点呢?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace parallelDemo
{
//这是一个冒泡排序的排序类,里面需要传入一个数组,一个比较器就好,那么就排好队了
class BubbleSorter {
static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison) {
bool swap = true;

do{
swap = false;
for (int i = 0; i < sortArray.Count - 1; i++) {
if(comparison(sortArray[i + 1],sortArray[i])){
T temp = sortArray[i];
sortArray[i] = sortArray[i + 1];
sortArray[i + 1] = temp;
swap = true;
}
}
}while(swap);
}
}

class Student {
public string name { get;private set;}
public double score { get;private set;}

public override string ToString()
{
return string.Format("{0},{1:C}",name,score);
}

public Student(string name,double score) {
this.name = name;
this.score = score;
}
//这是一个比较规则,结合BubbleSorter类,最终实现降序排列。
public static bool compareScore(Student s1,Student s2) {
return s1.score > s2.score;
}
}

class Program
{
static void Main(string[] args)
{
//parallelForDemo1();

//实例化一个数组
Student[] students =
{
new Student("小明",56.3),
new Student("小红",84.5),
new Student("小刚",76.2),
new Student("壮壮",99.9),
new Student("小马",80),
new Student("皇帝",100),
new Student("海涛",86.9)
};
//排序
BubbleSorter.Sort(students, Student.compareScore);
//打印排序结果
foreach(var student in students){
Console.WriteLine(student);
}
Console.ReadLine();
}
}
}


你现在可以很轻松的对其他对象中的数字字段进行排序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: