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)的概念.类型参数使得设计类和方法时,不必确定一个或多个具 ...
随机推荐
- 在ubuntu下利用minicom实现串口通信
windos有串口调试助手,linux下也有这样的工具——minicom.不过,minicom和linux下的许多工具都一样,也是命令行模式,没有图形化界面供我们享受.作为一款串口调试工具,虽然难看但 ...
- POJ 2406 Power Strings 1961的简化版,kmp的next数组的应用
题目: http://poj.org/problem?id=2406 跟1961差不多,题解就不写了,一开始理解错题了,导致WA一次. #include <stdio.h> #includ ...
- SDWebImage 详解
一.SDWebImage介绍 1.在项目的开发过程中,我们经常会用到异步加载图片的功能,先从网络上异步下载图片,然后通过UIImageView显示在屏幕上.这是一个经常使用的功能,基本上所有的联网应用 ...
- git操作回顾:
1. git查看自己的本地分支: ***:~/mysite/mysite$ git branch * master 2. 查看远程分支: ***:~/mysite/mysite$ git branch ...
- BZOJ 1640: [Usaco2007 Nov]Best Cow Line 队列变换
Description FJ打算带着他可爱的N (1 ≤ N ≤ 2,000)头奶牛去参加"年度最佳老农"的比赛.在比赛中,每个农夫把他的奶牛排成一列,然后准备经过评委检验. 比赛 ...
- PCB快速打样规范
基本情况 板材为FR-4,板厚1.6mm 板材铜厚为1/2oz,成品铜厚为1oz(加工过程中的沉铜工艺会让铜层增加厚度) 绿油白字 喷锡工艺 最小孔内铜厚1.27um 电铜18 ...
- block的是发送信号的线程,又不是处理槽函数的线程
请问UI线程给子线程发信号,应该用哪种连接方式? 如果子线程正在执行一个函数,我发射信号去执行子线程的另一个函数,那么此时子线程到底会执行什么呢? 用信号量做的同步.第一把信号槽的事件丢到线程的事件队 ...
- HTML input标签的checked属性与Razor解析
在HTML中,input标签可以通过type属性设置为checkbox.同时,也就包含了一个checked属性.对于这个checked属性,有一个特别的地方就是,它可以不需要属性值就可以表示是否选择了 ...
- 无法自动调试 未能调试远程过程。这通常说明未在服务器上启用调试 WCF 托管在IIS上
解决方案,把新建的网站的app.config修改下配置 <system.web> <!-- 设置 compilation debug="true" 可将调试符号插 ...
- USACO3.43Electric Fence(pick定理)
忘记pick定理是什么了 想枚举来着 ..没枚出来 有篇pick定理的证明 貌似挺好 也没太看懂 /* ID: shangca2 LANG: C++ TASK: fence9 */ #include ...