通过委托实现灵活排序
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(); } } }
你现在可以很轻松的对其他对象中的数字字段进行排序。
相关文章推荐
- Mysql 技术内幕(二)
- 爬虫工程师要求
- JavaScript 全选函数的实现
- java中jdbc事务管理
- servlet的转发和重定向
- leetcode179-Largest Number(把数组排成最大的数)
- KEIL编译环境优化等级说明
- HashTable和HashMap区别
- 游览器中javascript的执行过程
- ubuntu安装php常见错误集锦
- 批量修改文件后缀名、批量删除相同后缀名的文件
- HQL查询及Hibernate对c3p0连接池的支持
- POJ-1821 Fence(单调队列优化DP)
- vi配置文件
- 【Java学习-J.160611.0.21】Servlet基础四 cookie部分
- windows 命令
- 常用正则表达式大全!
- java for 的用法总结
- 关于Visual Studio 2013 编译 multi-byte character set MFC程序出现 MSB8031 错误的解决办法
- 正则应用