/*

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的更多相关文章

  1. .NET Framework System.Array.Sort 数组类,加深对 IComparer、IComparable 以及泛型委托、匿名方法、Lambda 表达式的理解

    本文内容 自定义类 Array.Sort 参考资料 System.Array.Sort 有很多对集合的操作,比如排序,查找,克隆等等,你可以利用这个类加深对 IComparer.IComparable ...

  2. Comparer<T> IComparer<T> IComparable<T>

    Comparer<T>.Default Property Comparer<T>.Default doesn't use your FooComparer class. It ...

  3. IComparer 与 IComparable

    static void Main() { var people = new ArrayList(); people.AddRange(new ArrayList { }, }, }, } }); Co ...

  4. Icomparer和Icomparable集合排序

    c#中实现对象集合的排序可以使用ArrayList中的Sort()方法,而有比较才能谈排序,因为不是基本类型(如string ,int.double......等)所以.NET Framework不可 ...

  5. IComparer、IComparable、StringComparison枚举、CultureInfo 的用法

    IEnumerable<T> 和 IEnumerator<T>.泛型版本是新式代码的首要选项. InvariantCulture:程序间.程序数据库.程序网络交互用Invari ...

  6. C#中如何使用IComparable<T>与IComparer<T>接口(转载)

    本分步指南描述如何使用两个接口: IComparer和IComparable.在同一篇文章中讨论这些接口有两个原因.经常在一起,使用这些接口和接口类似 (并且有相似的名称),尽管它们用于不同用途. 如 ...

  7. C# 中的IComparable和IComparer

    前言 在开发过程中经常会遇到比较排序的问题,比如说对集合数组的排序等情况,基本类型都提供了默认的比较算法,如string提供了按字母进行排序,而int整数则是根据整数大小进行排序.但是在引用类型中(具 ...

  8. C#语言各个版本特性(二)

    二.排序Product 1.按名称对产品进行排序,以特定顺序显示一个列表的最简单方式就是先将列表排序,再遍历并显示其中的项. C#1.1 使用IComparer对ArrayList进行排序 produ ...

  9. 转载:C#中的泛型

    泛型(generic)是C#语言2.0和通用语言运行时(CLR)的一个新特性.泛型为.NET框架引入了类型参数(type parameters)的概念.类型参数使得设计类和方法时,不必确定一个或多个具 ...

随机推荐

  1. Python深入学习笔记(一)

    写在前面的话 从08年接触Python到现在,断断续续地使用,到如今Python已经成为日常事物处理.科研实验,甚至工程项目的主力语言,主要因为其敏捷性和快速实现的能力.虽然看了一些Python的教程 ...

  2. ThinkPHP学习手记——环境搭建

    怀着激动的心情打开了thinkPHP的文档,开启了第一次php框架学习. 下载 ThinkPHP最新版本可以在官方网站(http://thinkphp.cn/down/framework.html) ...

  3. 工作总结:文件对话框的分类(C++)

    原文地址:http://www.jizhuomi.com/software/173.html 文件对话框分为打开文件对话框和保存文件对话框,相信大家在Windows系统中经常见到这两种文件对话框.例如 ...

  4. 广州麒麟网络工作室 qlgame eninge(anroid) opengles c++ matrix

    在opengles中,采用的是可编程渲染管线,矩阵需要自己实现! 先说一下矩阵的理论: 参考一下资料:http://blog.sina.com.cn/s/blog_6084f588010192ug.h ...

  5. 杂烩:QWidget、QGraphics、QtQuick

    一说起Qt 大都会想起Qt的GUI编程,具体到某个类的话,最多的就是QWidget类及其子类了. 其实Qt中还有基于项的图形视图,具体来说QGraphicsView,QGraphicsScene,QG ...

  6. QWidget属性,函数的学习

    我把所有属性重新按功能排了一遍,这样才能灌到自己脑子里,并且方便自己以后查找: -------------------- 颜色/渲染方式 -----------------------QWidget: ...

  7. NavigationDrawer+Fragment实现侧滑菜单效果

    学习了NavigationDrawer 官方Support包中的SlidingMenu版本,练了下手.用到了ListView中item不同的布局 以后会升级加上ViewPager和GridView实现 ...

  8. 2.linux下Makefile编写规范

    转自陈皓 (CSDN) 概述—— 什么是makefile?或许很多Winodws的程序员都不知道这个东西,因为那些Windows的IDE都为你做了这个工作,但我觉得要作一个好的和 profession ...

  9. 微软开放技术开发了适用于 Windows Azure 移动服务的开源 Android SDK

     发布于 2014-02-10 作者 陈 忠岳 为进一步实现连接微软与非微软技术的目标,微软开放技术有限公司开发了适用于 Windows Azure 移动服务的 Android SDK,由Scot ...

  10. Android 应用页面延缓载入

    1.新建一个线程,使用handle的延缓运行线程 new Handler().postDelayed(new Runnable() { // 为了减少代码使用匿名Handler创建一个延时的调用 pu ...