泛型 List中的Sort方法
来源:互联网 发布:知乎 修改一句话介绍 编辑:程序博客网 时间:2024/06/05 19:46
常用的两种使用scort()进行排序的方法
- 对于List按照某一个字段的值进行排序,使用系统提供的sort方法进行排序,需要继承ICompare接口实现参数中的CompareTo方法,注意参数一定是Object。CompareTo方法只能进行两个数据的比较,但是系统可以实现对整个list中的数据的排序。
List<Student> stuList = new List<Student>(); stuList.Add(s1); stuList.Add(s2); stuList.Add(s3); stuList.Add(s4); stuList.Add(s5); stuList.Add(s6); for (int i = 0; i < stuList.Count; i++) { Console.WriteLine(stuList[i]); } Console.WriteLine("------------------------"); stuList.Sort(); for (int i = 0; i < stuList.Count; i++) { Console.WriteLine(stuList[i]); }public int CompareTo(object other) { return this.Age - ((Student)other).Age; }
ps:可以通过改变this.Age和other.Age的顺序控制是升序还是降序,方法的返回值必须和接口中的方法保持一致
- 参考多个字段进行排序
自己实现方法,方法的返回值必须是int,在sort中使用lambda表达式实现排序
可以通过设置权重来控制字段的优先级
List<Student> stuList = new List<Student>(); stuList.Add(s1); stuList.Add(s2); stuList.Add(s3); stuList.Add(s4); stuList.Add(s5); 多个方法之间要使用 + 号 stuList.Sort(((x, y) => x.sortByAge(y) * 4 + x.sortByChinese(y)));//系统规定必须是int for (int i = 0; i < stuList.Count; i++) { Console.WriteLine(stuList[i]); }public int sortByAge(Student s) { int result = this.Age - s.Age; return result==0?0:(result>0?1:-1); } public int sortByChinese(Student s) { int result= (int)(s.Chinese-this.Chinese);//变量的位置确定了正序还是倒序 return result == 0 ? 0 : (result > 0 ? 1 : -1); }
阅读全文
0 0
- 泛型 List中的Sort方法
- java 泛型 集合嵌套 Collections中的sort(list)方法
- list中的Sort、Exists方法使用
- List.Sort 方法()
- list sort方法调研
- java 中的 collections.sort() 方法对list的排序
- 用Java集合中的Collections.sort方法对list排序
- 关于std::list中的sort()
- 关于std::list中的sort()
- list sort 自定义 key 方法
- 【Python】Python3 List sort()方法
- python中的sort方法
- javascript中的sort()方法
- Python中的sort()方法
- js中的sort()方法
- javascript中的sort()方法
- Java中的List<JavaBean>以javabean中的某一属性排序之Collections.sort方法
- 用Java集合中的Collections.sort方法对list排序的两种方法
- RecyclerView实现购物车的全选、反选功能
- kubernetes1.5.2集群部署过程--安全模式
- Ericsson Ridea从入门到精通(三)
- Elasticsearch Reference 5.5 中文翻译4
- OGV格式转成MP4格式
- 泛型 List中的Sort方法
- 计算从整数1到n之间,所有1的个数的和
- qq空间h5页面,如何在微信中直接打开qq空间链接却不需要登陆qq账号密码
- python-3 元组
- c语言实现二叉树的建立与前序、中序、后序、层序遍历
- hdu 3172 Virtual Friends(加权并查集)
- map、list查询速度
- Maven详解(六)------ 生命周期
- 数值计算和SVM讲解(下)