CSharp - Comparison between IComparer and IComparable
/*
Author: Jiangong SUN
*/
I've already written an article introducing the usage of comparer here. In this article I'll compare the usage of IComparable and IComparer with examples.
Important difference: A class can have only one Comparable, but multiple Comparer.
Here I have a class Student with different properties, which will be used as sorting criterias.
public class Student : IComparable<Student>
{
public string LastName { get; set; }
public string FirstName { get; set; }
public int Age { get; set; }
public int Class { get; set; }
}
Firstly, I want class Student to implement interface IComparable, and I must override method CompareTo of interface IComparable. In this method I sort Student list in an ascending order.
//class who implement interface IComparable, must implement CompareTo method
public class Student : IComparable<Student>
{
public string LastName { get; set; }
public string FirstName { get; set; }
public int Age { get; set; }
public int Class { get; set; }
//CompareTo method compare itself to another object
public int CompareTo(Student student)
{
return LastName.CompareTo(student.LastName);
}
}
In this way, Student list will be sorted by LastName in an ascending order.
Next, I'll create 3 comparers who will use the rest 3 properties as sorting criteria.
//Comparer 1
//class who implement interfce IComparer, must implement Compare method
public class OrderByAgeAscending : IComparer<Student>
{
//Compare method compares two objects
public int Compare(Student x, Student y)
{
if (x.Age.CompareTo(y.Age) < 0)
{
return -1;
}
if (x.Age.CompareTo(y.Age) == 0)
{
return 0;
}
return 1;
}
} //Comparer 2
public class OrderByClassDescending : IComparer<Student>
{
public int Compare(Student x, Student y)
{
if (x.Class.CompareTo(y.Class) < 0)
{
return 1;
}
if (x.Class.CompareTo(y.Class) == 0)
{
return 0;
}
return -1;
}
} //Comparer 3
public class OrderByFirstNameAscending : IComparer<Student>
{
public int Compare(Student x, Student y)
{
if (x.FirstName.CompareTo(y.FirstName) < 0)
{
return -1;
} if (x.FirstName.CompareTo(y.FirstName) == 0)
{
return 0;
}
return 1;
}
}
Now I will create a new Student list with some Students and try to sort them with comparable and comparer.
Firstly, I will create a list.
var s1 = new Student() { LastName = "charles", FirstName = "charles", Age = 27, Class = 15 };
var s2 = new Student() { LastName = "viz", FirstName = "newton", Age = 20, Class = 30 };
var s3 = new Student() { LastName = "la", FirstName = "aba", Age = 2, Class = 2 };
var students = new List<Student>() { s1, s2, s3 };
Then, I will sort the list with comparable. I just need to call Sort() method, it will use the CompareTo() method I've created.
//IComparable: sort by last name
students.Sort();
Display(students, "IComparable OrderByLastName:");
And then, I will use the 3 comparers to sort the list.
//Comparer 1: order by age
var c1 = new OrderByAgeAscending();
students.Sort(c1);
Display(students, "Comparer OrderByAgeAscending:"); //Comparer 2: order by class
var c2 = new OrderByClassDescending();
students.Sort(c2);
Display(students, "Comparer OrderByClassDescending:"); //Comparer 3: order by first name
var c3 = new OrderByFirstNameAscending();
students.Sort(c3);
Display(students, "Comparer OrderByFirstNameAscending");
And there are an Display() method who is in charge of display the student information.
public static void Display(List<Student> students, string comparerName)
{
Console.WriteLine(comparerName);
foreach (var student in students)
{
Console.WriteLine("last name: " + student.LastName + "; first name: " + student.FirstName + "; age: " + student.Age + "; class: " + student.Class);
}
}
Now, let's see the results:
Right now, we are arrived at the end of the article. I hope you can find useful information here. Enjoy coding!
references:
http://addinit.com/node/50
http://www.codeproject.com/Articles/42839/Sorting-Lists-using-IComparable-and-IComparer-Inte
CSharp - Comparison between IComparer and IComparable的更多相关文章
- .NET Framework System.Array.Sort 数组类,加深对 IComparer、IComparable 以及泛型委托、匿名方法、Lambda 表达式的理解
本文内容 自定义类 Array.Sort 参考资料 System.Array.Sort 有很多对集合的操作,比如排序,查找,克隆等等,你可以利用这个类加深对 IComparer.IComparable ...
- Comparer<T> IComparer<T> IComparable<T>
Comparer<T>.Default Property Comparer<T>.Default doesn't use your FooComparer class. It ...
- IComparer 与 IComparable
static void Main() { var people = new ArrayList(); people.AddRange(new ArrayList { }, }, }, } }); Co ...
- Icomparer和Icomparable集合排序
c#中实现对象集合的排序可以使用ArrayList中的Sort()方法,而有比较才能谈排序,因为不是基本类型(如string ,int.double......等)所以.NET Framework不可 ...
- IComparer、IComparable、StringComparison枚举、CultureInfo 的用法
IEnumerable<T> 和 IEnumerator<T>.泛型版本是新式代码的首要选项. InvariantCulture:程序间.程序数据库.程序网络交互用Invari ...
- C#中如何使用IComparable<T>与IComparer<T>接口(转载)
本分步指南描述如何使用两个接口: IComparer和IComparable.在同一篇文章中讨论这些接口有两个原因.经常在一起,使用这些接口和接口类似 (并且有相似的名称),尽管它们用于不同用途. 如 ...
- C# 中的IComparable和IComparer
前言 在开发过程中经常会遇到比较排序的问题,比如说对集合数组的排序等情况,基本类型都提供了默认的比较算法,如string提供了按字母进行排序,而int整数则是根据整数大小进行排序.但是在引用类型中(具 ...
- C#语言各个版本特性(二)
二.排序Product 1.按名称对产品进行排序,以特定顺序显示一个列表的最简单方式就是先将列表排序,再遍历并显示其中的项. C#1.1 使用IComparer对ArrayList进行排序 produ ...
- 转载:C#中的泛型
泛型(generic)是C#语言2.0和通用语言运行时(CLR)的一个新特性.泛型为.NET框架引入了类型参数(type parameters)的概念.类型参数使得设计类和方法时,不必确定一个或多个具 ...
随机推荐
- NSString NSMutableString copy mutableCopy retain weak strong整合
copy retain assign的差别在于对象属性的set方法 NSString 与 NSMutableString NSString是不可变字符串对象,这句话的意思,结合代码: #import ...
- android studio中文乱码的解决方法【转】
一. 在android的源文件中的乱码问题 Android Studio安装后发现所有的中文,不管是界面上的还是输出的log中的中文都变成小框框,具体的解决方法如下, 可以肯定是字体的问题 解决:菜单 ...
- log的6种等级
在Java中,log有6种等级,从低到高为: (1)TRACE:用于展现程序执行的轨迹 (2)DEBUG:用于协助低层次的调试 (3)INFO:用于基本高层次的诊断信息,在长时间运行的代码段开始运行及 ...
- win7 任务计划 任务映像已损坏或篡改(异常来自HRESULT:0x80041321)
转自win7 任务计划 任务映像已损坏或篡改(异常来自HRESULT:0x80041321) 请这样操作: 1. 以管理员身份运行命令提示符并执行命令 chcp 437 schtasks /query ...
- VMware配置回环地址用于测试
我们在开发过程中,很可能需要一台服务器用于测试,在这种环境下,我们很可能需要用到vmware来构建这样的开发环境.但如果当前处在一个离线,或是不在网内的环境下,我们所搭建的环境有可能无法 ...
- 编译Firebird的源码
编译步骤:一.下载所需的软件 1.下载FB2.0 RC4 http://optusnet.dl.sourceforge.net/sourceforge/firebird/Firebird ...
- decode_json 必须是unicode形式的字符
centos6.5:/root/test#cat a1.pl use JSON qw/encode_json decode_json/; use Encode; my $data = [ { 'nam ...
- 3.android下Makefile编写规范
随着移动互联网的发展,移动开发也越来越吃香了,目前最火的莫过于android,android是什么就不用说了,android自从开源以来,就受到很多人的追捧.当然,一部人追捧它是因为它是Google开 ...
- 《Gulp 入门指南》 : 使用 gulp 压缩 JS
<Gulp 入门指南> : 使用 gulp 压缩 JS 请务必理解如下章节后阅读此章节: 安装 Node 和 gulp 访问论坛获取帮助 压缩 js 代码可降低 js 文件大小,提高页面打 ...
- ASP.Net4.0中新增23项功能
这篇文章介绍Visual Studio 2010 (ASP.Net 4.0)的新功能. 1.代码片段(Code Snippets): 代码段是预先开发的代码模板,可以节省我们对有关语法思考的时间.在V ...