C#基础之数组排序,对象大小比较
从个小例子开始:
|
1
2
3
|
int[] intArray = new int[]{2,3,6,1,4,5};Array.Sort(intArray);Array.ForEach<int>(intArray,(i)=>Console.WriteLine(i)); |
这个例子定义了一个int数组,然后使用Array.Sort(arr)静态方法对此数组进行排序,最后输出排序后的数组。以上例子将毫无意外的依次输出1,2,3,4,5,6.
为什么Array的Sort方法可以正确的对int数组进行排序呢,我们自定义类可以吗?试试看,如下代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public class Student{ public int Age { get; set; } public string Name { get; set; } public int Score { get; set; }}static void Main(string[] args){ Student[] students = new Student[]{ new Student(){Age = 10,Name="张三",Score=70}, new Student(){Age = 12,Name="李四",Score=97}, new Student(){Age = 11,Name="王五",Score=80}, new Student(){Age = 9,Name="赵六",Score=66}, new Student(){Age = 12,Name="司马",Score=90}, }; Console.WriteLine("--------------默认排序输出--------"); Array.Sort(students); Array.ForEach<Student>(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}",s.Name,s.Age,s.Score))); Console.Read();} |
我们定义了Student类然后同样对他的数组进行排序,程序正确的编译通过,但是运行出错,运行时抛出了异常:System.InvalidOperationException{"Failed to compare two elements in the array."},这个异常的InnerException是ArgumentException{"At least one object must implement IComparable."};运行时异常说明:我们要使用Array.Sort(arr)静态方法,必须得保证数组中有一个元素实现IComparable接口。既然如此我们就让Student类实现IComparable接口.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class Student :IComparable{ public int Age { get; set; } public string Name { get; set; } public int Score { get; set; } /// <summary> /// 实现IComparable接口,用Age做比较 /// </summary> /// <param name="obj">比较对象</param> /// <returns>比较结果</returns> public int CompareTo(object obj) { if (obj is Student) { return Age.CompareTo(((Student)obj).Age); } return 1; }} |
在Student类中实现了IComparable接口,在CompareTo方法中比较Student的Age属性,这一次再次编译运行,程序正常的输出了按照年龄排序的Student数组。
假如说我们要对Student的Score属性进行排序该怎么办呢? Student类实现的IComparable接口只能按照一种属性排序呀。
这个是很容易实现的.net的类库开发者早为我们准备了另一个接口IComparer<T>接口用来实现比较类型T的两个实例。如下StudentScoreComparer类实现了对Student按照Score属性比较的IComparer<Student>
|
1
2
3
4
5
6
7
|
public class StudentScoreComparer : IComparer<Student>{ public int Compare(Student x, Student y) { return x.Score.CompareTo(y.Score); }} |
现在我们可以使用下面代码对Student数组按照Score属性进行排序:
|
1
2
3
|
Console.WriteLine("----------按分数排序输出------------");Array.Sort(students, new StudentScoreComparer());Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}", s.Name, s.Age, s.Score))); |
不过一个简单的按照Score属性排序,再定义一个类是不是有点大题小作呀,有没有更好的办法呢?当然有. .net为我们准备了比较对象大小的委托Comparison<T>我们可以使用拉姆达表达式或者匿名委托直接排序,如下代码实现:
|
1
2
3
|
Console.WriteLine("----------按分数排序输出----------");Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}", s.Name, s.Age, s.Score))); |
完整代码示例如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace SortingInCSharp{ class Program { public class Student : IComparable { public int Age { get; set; } public string Name { get; set; } public int Score { get; set; } /// <summary> /// 实现IComparable接口,用Age做比较 /// </summary> /// <param name="obj">比较对象</param> /// <returns>比较结果</returns> public int CompareTo(object obj) { if (obj is Student) { return Age.CompareTo(((Student)obj).Age); } return 1; } } static void Main(string[] args) { Student[] students = new Student[]{ new Student(){Age = 10,Name="张三",Score=70}, new Student(){Age = 12,Name="李四",Score=97}, new Student(){Age = 11,Name="王五",Score=80}, new Student(){Age = 9,Name="赵六",Score=66}, new Student(){Age = 12,Name="司马",Score=90}, }; Console.WriteLine("--------------默认排序输出--------"); Array.Sort(students); Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}", s.Name, s.Age, s.Score))); Console.WriteLine("----------按分数排序输出------------"); Array.Sort(students, new StudentScoreComparer()); Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}", s.Name, s.Age, s.Score))); Console.WriteLine("----------按分数排序输出----------"); Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score)); Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}", s.Name, s.Age, s.Score))); Console.Read(); } public class StudentScoreComparer : IComparer<Student> { public int Compare(Student x, Student y) { return x.Score.CompareTo(y.Score); } } }} |
总结:
在C#中有三个关于比较对象大小的接口,分别是IComparable、IComparable<T>和IComparer<T>。 IComparable和IComparable<T>是类本身实现的在实例之间比较大小的行为定义。IComparer<T>是定义在被比较类之外的专门比较两个T类型对象大小的行为,另外还有一个用于比较的委托定义Comparison<T>可以让我们用拉姆达表达式或者匿名委托或方法更方便的排序。
C#基础之数组排序,对象大小比较的更多相关文章
- 【C#】基础之数组排序,对象大小比较(对比器)
C#基础之数组排序,对象大小比较 原文链接:[OutOfMemory.CN] 从个小例子开始: 1 2 3 int[] intArray = new int[]{2,3,6,1,4,5}; Array ...
- C++类对象大小的计算
(一)常规类大小计算 C++类对象计算需要考虑很多东西,如成员变量大小,内存对齐,是否有虚函数,是否有虚继承等.接下来,我将对此举例说明. 以下内存测试环境为Win7+VS2012,操作系统为32位 ...
- Java基础-IO流对象之转换流(InputStreamReader与OutoutStreamWriter)
Java基础-IO流对象之转换流(InputStreamReader与OutoutStreamWriter) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.转换流概述 我们之前 ...
- 两种计算Java对象大小的方法
之前想研究一下unsafe类,碰巧在网上看到了这篇文章,觉得写得很好,就转载过来.原文出处是: http://blog.csdn.net/iter_zc/article/details/4182271 ...
- Java对象大小计算
这篇说说如何计算Java对象大小的方法.之前在聊聊高并发(四)Java对象的表示模型和运行时内存表示 这篇中已经说了Java对象的内存表示模型是Oop-Klass模型. 普通对象的结构如下,按64位机 ...
- (转)JS获取当前对象大小以及屏幕分辨率等
原文 JS获取当前对象大小以及屏幕分辨率等 <script type="text/javascript">function getInfo(){ var ...
- JS获取当前对象大小以及屏幕分辨率等...
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta nam ...
- 【Javascript Demo】JS获取当前对象大小以及屏幕分辨率等
效果如下: 代码如下: <html> <head> <title>获取当前对象大小以及屏幕分辨率等</title> <body> <d ...
- java调优随记-java对象大小
在java中,基本数据类型的大小是固定.但是java对象的大小是不固定的,需要通过计算. 在java中,一个空对象(没有属性和方法的对象)在堆中占用8byte,比如 Object obj = new ...
随机推荐
- HTTP协议详细总结
HTTP超文本传输协议,是WWW上应用的最多的协议.了解和掌握HTTP协议是对程序人员的基本要求. 转载请注明出处 http://www.cnblogs.com/zrtqsk/p/3746891.ht ...
- java 利用JAX-RS快速开发RESTful 服务
JAX-RS(Java API for RESTful Web Services)同样也是JSR的一部分,详细规范定义见 https://jcp.org/en/jsr/detail?id=311 .从 ...
- 高性能JavaScript 循环语句和流程控制
前言 上一篇探讨了达夫设备对于代码性能的影响,本文主要探讨并且测试各种常见的循环语句的性能以及流程控制中常见的优化. 循环语句 众所周知,常用的循环语句有for.while.do-while以及for ...
- 开源Asp.Net Core小型社区系统
源码地址:Github 前言 盼星星盼月亮,Asp.Net Core终于发布啦!! Asp.Net发布时我还在上初中,没有赶上.但是Asp.Net Core我从beta版本便一直关注.最初项目名叫As ...
- 如何在Vue2中实现组件props双向绑定
Vue学习笔记-3 前言 Vue 2.x相比较Vue 1.x而言,升级变化除了实现了Virtual-Dom以外,给使用者最大不适就是移除的组件的props的双向绑定功能. 以往在Vue1.x中利用pr ...
- Redis Sentinel:集群Failover解决方案(转载)
本文转载自:http://shift-alt-ctrl.iteye.com/blog/1884370 文中的配置例子,还有failover过程中触发的订阅事件具有很好的参考价值. Redis sent ...
- nios II--实验6——串口软件部分
软件开发 首先,在硬件工程文件夹里面新建一个software的文件夹用于放置软件部分:打开toolsàNios II 11.0 Software Build Tools for Eclipse,需要进 ...
- [ZOJ2760]How Many Shortest Path(floyd+最大流)
题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1760 题意:给你一个一个n*n(n<=100)的有向图,问你从s到 ...
- linux svn搭建
1 安装: yum install subversion 2 查看svn安装信息: rpm -ql subversion 3 创建svn根目录: svnserve -d -r /svn 4 进入/sv ...
- webService访问加密-Soapheader
WebService head加密,可以对 WebService设置访问用户名和密码,增强 WebService的安全性 使 WebService只能被授权用户使用. 具体实现步骤: 1. 定义一个 ...