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)的概念.类型参数使得设计类和方法时,不必确定一个或多个具 ...
随机推荐
- IE filter & z-index bug
对最近遇到的2个问题的一点总结. 1.IE filter & z-index 重构后的首页即将上线,测试提出fix导航条扩展菜单在ie789滚动后一段无法显示的问题. 疑云重重: 这个问题一开 ...
- java api如何获取kafka所有Topic列表,并放置为一个list
kafka内部所有的实现都是通过TopicCommand的main方法,通过java代码调用API,TopicCommand.main(options)的方式只能打印到控制台,不能转换到一个list. ...
- Adobe Flash Builder 4.7下载地址及破解补丁(32位&64位)
Adobe FlashBuilder 4.7是开发flex的利器,能显著提高flex的开发效率.最新版的是4.7,去官网上下载时每次都要登录才能下载,特麻烦,这次下载时就把相关的下载地址给记录了下来, ...
- Learning WCF 书中的代码示例下载地址
Learning WCF Download Example Code 第一个压缩文件LearningWCF.zip是VS2005创建的项目,不要下载这个. 建议下载VS2008版的,以及Media
- ADO.NET 代码示例
转自:http://msdn.microsoft.com/zh-cn/library/dw70f090 本主题中的代码列表演示如何使用下面的 ADO.NET 技术从数据库中检索数据: ADO.NET ...
- 蓝桥杯--算法训练 区间k大数查询
算法训练 区间k大数查询 时间限制:1.0 ...
- HDU-2710 Max Factor
看懂: Max Factor Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) T ...
- 圣诞福利到!51Testing邀你一起来狂欢!有礼就是任性~(≧▽≦)/~
“我想变成一棵树,一棵只为你存在的圣诞树,顶上最大最亮的那颗星是我的真心,下面挂满我对你的祝福. 你的关注是我的幸福,你的肯定是我的力量,而我将用更多精彩的内容,用心的分享,给你下一个一整年的 精彩! ...
- NodeAsp——像开发NodeJS应用一样玩转ASP
NodeAsp是一套Classic ASP框架,借鉴了NodeJS的模块化思想,让您可以使用全新的理念愉快地书写ASP程序. NodeAsp使用遵循CommonJS规范的require,完全兼容Nod ...
- [leetcode]重建二叉树(先序和终须) 中序遍和后续
分割后长度相等,就是参数麻烦,p,先序的起始点, ib,ie 终须的结束和开始. /** * Definition for binary tree * public class TreeNode { ...