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)的概念.类型参数使得设计类和方法时,不必确定一个或多个具 ...
随机推荐
- SortedList的用法
1.SortedList定义 System.Collections.SortedList类表示键/值对的集合,这些键值对按键排序并可按照键和索引访问.SortedList 在内部维护两个数组以存储列表 ...
- Newtonsoft post Json 日期格式处理
Newtonsoft.Json.Converters.IsoDateTimeConverter DateTimeConverter = new Newtonsoft.Json.Converters. ...
- mvc4 membership, [Win32Exception (0x80004005): The system cannot find the file specified]
public class UsersContext : DbContext { public UsersContext() : base("conn1") //change the ...
- 数据库之--- SQLite 语句
一. 基础创表操作: 1. 创建表 CREATE TABLE IF NOT EXISTS t_dog(name text, age bolb, weight real); 2. 插入记录 INSERT ...
- 定位- CLGeoencoder - 反编码
#import "ViewController.h" #import "MBProgressHUD+MJ.h" #import <CoreLocation ...
- UI控件切圆角
1. xib下设置View圆角 这个很简单, 只需要重写 - (void)drawRect:(CGRect)rect 方法就行了 1 2 3 4 5 6 - (void)drawRect:(CGRe ...
- delphi xe5 android 开发实现手机打电话和发短信
转载自 http://www.raysoftware.cn/ 其实都可以通过intent和URI调用系统功能.Windows程序员可以理解成是ShellExecute.这个是万金油.可以有调用各种功 ...
- Bootstrap 分页插件 ajax获取数据显示
Bootstrap 分页插件 ajax获取数据显示 标签(空格分隔): bootstrap 文章的内容是使用bootstrap-paginator进行分页,使用ajax获取后台数据.渲染. 1. 版本 ...
- awsomeplayer结构认识
把这个搞明白,算是顿悟的一个真实例子.怎么也搞不懂的架构,突然就想明白了.不过这其实是一个思维的过程. 当然如果你想明白这些东西,至少要非常清楚一个概念:接口. 我只是一个半路出家的开发者,我真正明白 ...
- 【Xamarin开发 Android 系列 7】 Android 结构基础(下)
原文:[Xamarin开发 Android 系列 7] Android 结构基础(下) *******前期我们不打算进行太深入的东西,省的吓跑刚进门的,感觉门槛高,so,我们一开始就是跑马灯一样,向前 ...