/*

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. SDWebImage 详解

    一.SDWebImage介绍 1.在项目的开发过程中,我们经常会用到异步加载图片的功能,先从网络上异步下载图片,然后通过UIImageView显示在屏幕上.这是一个经常使用的功能,基本上所有的联网应用 ...

  2. delphi xe5 android 服务端和手机端的源码下载

    xe5 android的服务端和手机客户端的源代码下载地址 http://files.cnblogs.com/nywh2008/AndroidTest.rar

  3. UML类图的6中关系

    引用自: http://blog.csdn.net/tianhai110/article/details/6339565 UML类图分为如下四种关系: 1.  泛化 (Generalization)  ...

  4. python中self.__class__

    1. python中的self python中的self就相当于C++中的this指针也就是指向对象本身的指针self.name = name 就是当前对象的成员变量name赋值为name. 2.py ...

  5. BZOJ 1660: [Usaco2006 Nov]Bad Hair Day 乱发节

    Description Input * Line 1: 牛的数量 N. * Lines 2..N+1: 第 i+1 是一个整数,表示第i头牛的高度. Output * Line 1: 一个整数表示c[ ...

  6. XSS解决方案系列之四:关于编码

    本文准备说明以下几个问题: 1. 关于重复编码的问题 2. 关于编码的多种形式的问题 3. 关于编码的几个常见问题 [说明] 本文所述编码是指encode,可以理解为转义,而不是编程序写代码. 编码或 ...

  7. Android 制作一个网页源代码浏览器(HttpURLConnection)

    package com.wuyou.htmlcodeviewer; import android.os.Bundle; import android.os.Handler; import androi ...

  8. 【HDU 5370】 Tree Maker(卡特兰数+dp)

    Tree Maker Problem Description Tree Lover loves trees crazily. One day he invents an interesting gam ...

  9. Android内存优化之——static使用篇

    在Android开发中,我们经常会使用到static来修饰我们的成员变量,其本意是为了让多个对象共用一份空间,节省内存,或者是使用单例模式,让该类只生产一个实例而在整个app中使用.然而在某些时候不恰 ...

  10. WebBrowser控件跨域访问页面内容

    原文出处 :http://blog.csdn.net/nocky/article/details/6056802 源码出处:http://www.codecentrix.com/blog/wnd2do ...