Sorting ArrayList Containing User Defined Types

原创 2004年08月24日 20:04:00
Introduction:

We all know about ArrayList and its functionlity, it is the dynamic array of the .Net Framework, where you can add, delete, search & sort objects in it. The issue we will descuss in this article is Sorting ArrayList.

Define the issue:

The problem is stated in MSDN in the definition of the Sort method it says: "Sorts the elements in the entire ArrayList using the IComparable implementation of each element". which means that any object in the ArrayList that you wish to sort must implement the IComparable interface. I think most of .Net Framework implements the IComparable interface like Int32,Int16...,String,Decimal etc.... but what about our own types??!! the Classes and structures we build ourselvs?? do we still able to sort them??!!! yes we can do that, but note that those will be complex type, which mean that you have to know what is the parameter you are going to use to sort your own defined types, and this what we are going to see in the next sections.

Note: :if you tried to sort and array or an ArrayList that is containing your defined type, and this type do not implement the IComparable interface, you will get an exception.

IComparable interface:

By looking in the MSDN, I found the IComparable interface has only one method, CompareTo which take only one parameter of type object, which mean it can accept any type, and returns an integer which mean the following:

  • Less than zero if this instance is less than obj.
  • Zero if this instance is equal to obj.
  • Greater than zero if this instance is greater than obj.

So all we have to do when building our own type is to implement the IComparable interface example:

public class Employee : System.IComparable
{
 //....code
 public int CompareTo(object obj)
 {
  //..implementation
 }
}

Now we will see how to implement the IComparable interface. First we will create a new class called Employee. This class will contain Employee name,ID,salary & department name, at the begining we will sort the according to Employee ID then we will see how to implement a parametrized sorting, so can sort by name and salary or anything else. So let's see the Empolyee Class

class Empolyee : System.IComparable
{
 private string m_EmpName;
 private string m_EmpDept;
 private int m_EmpID;
 private decimal m_EmpSalary;
  
 public Employee(int id, string name,string dept)
 {
  m_EmpID = id;
  m_EmpName = name;
  m_EmpDept = dept;
  m_EmpSalary = 0.0M;
 }
 public string Name
 {
  get{return m_EmpName;}
  set{m_EmpName=value;}
 }
 public string Department
 {
  get{return m_EmpDept;}
  set{m_EmpDept=value;}
 }
 public int ID
 {
  get{return m_EmpID;}
  set{m_EmpID=value;}
 }
 public decimal Salary
 {
  get{return m_EmpSalary;}
  set{m_EmpSalary=value;}
 }
 /// 
 /// Less than zero if this instance is less than obj. 
 /// Zero if this instance is equal to obj. 
 /// Greater than zero if this instance is greater than obj. 
 ///
 ///
 /// This method uses the predefined method Int32.CompareTo 
 ///
 public int CompareTo(object obj)
 {
  if(!(obj is Employee))
   throw new InvalidCastException("This object is not of type Employee");
  
  Employee emp = (Employee)obj;
  //no need to rewrite the code again, we have int.CompareTo ready to use
  return this.ID.CompareTo(emp.ID);
 }
}

As you see in that class, it is easy to implement the IComparable interface. and also I didn't write the code myself, I used the Int32.CompareTo method, cause it is already implemented to compare integers, but if you wish you can write it yourself, it will be like this:

if(this.ID < emp.ID)
 return -1;
else if(this.ID==emp.ID)
 return 0;
else
 return 1;

That was easy wasn't it?

Now when you add you Empolyees to an ArrayList, you can sort this ArrayList with no porblems, better than implement a sort algorithm to sort your own types.

What is Next:

Suppose you want to make several option for sorting!! like sorting by name or by salary??!! The implementation is too easy and simple, the solution I made is to create an enumiration with the values of sorting options:

public enum SortBy{ID,NAME,SALARY}

then I created a static property of type SortBy enum in my Employee class:

private static SortBy m_SortBy = SortBy.NAME;
public static SortBy SortBy
{
 get{return m_SortBy;}
 set{m_SortBy=value;}
}

then I modified the CompareTo method this way:

public int CompareTo(object obj)
{
 if(!(obj is Employee))
  throw new InvalidCastException("This object is not of type Employee");
 
 Employee emp = (Employee)obj;
 switch(m_SortBy)
 {
  case ArrayListSortingDemo.SortBy.ID:
   return this.ID.CompareTo(emp.ID);
  case ArrayListSortingDemo.SortBy.NAME:
   return this.Name.CompareTo(emp.Name);
  case ArrayListSortingDemo.SortBy.SALARY:
   return this.Salary.CompareTo(emp.Salary);
  default:
   goto case ArrayListSortingDemo.SortBy.NAME;
 }
  
}

Just simple switch..case statement.

and before calling the ArrayList.Sort, I set the Property Employee.SortBy to the sort value option.

I built a simple form that uses the Employee Class and store objects from it in the ArrayList, I'm using a combo box to select sort option, then I set the sort option and call the ArrayList.Sort method

the results is displayed in a ListBox

mosessaur_ArrayListSortScree.gif 

Download the code

You can do more complex sort options,but here I want to explain to core of sort in the Arrays and ArrayList.

Wish you all the best

Docker自定义网络和运行时指定IP

Docker 默认网络 Docker安装后,默认会创建下面三种网络类型: $ docker network ls NETWORK ID     NAME        DRIVER       SC...
  • sbxwy
  • sbxwy
  • 2018年01月03日 16:40
  • 29

iOS 在user defined runtime attributes(用户定义的运行时属性)改变UI

user defined runtime attributes(用户定义的运行时属性)是一个非常强大但是几乎没用过的功能 它在这里: 我们先看一下它的他用处,在Main.StoryBord里面添...
  • LG_sun
  • LG_sun
  • 2016年01月14日 18:36
  • 3553

ios中的实现属性显示在图形界面上进行修改的知识点

属性能够在Interface Builder的图形化界面进行设置 代码与代码之间的桥梁是两个关键字:IB_DESIGNABLE 和 IBInspectable . IBInspectable...
  • u012496940
  • u012496940
  • 2015年11月17日 20:39
  • 2054

Vuforia开发高阶三-用户自定义Target(第二部分)

前面介绍UDT基础开发,这里介绍怎么使用UDT的多Target对应不同模型的问题。  对于UDT的示例,我觉得有必要把这个类单独拿出来讲一下,  UserDefinedTargetEventH...
  • han15939423461
  • han15939423461
  • 2017年06月10日 14:08
  • 310

CAS 实现单点登录oos(2)

http://www.cnblogs.com/rwxwsblog/p/4954843.html   前面已经介绍了CAS服务器的搭建,详情见:搭建CAS单点登录服务器。然而前面只是简单地介绍...
  • lixld
  • lixld
  • 2016年08月25日 20:04
  • 866

一站式解决 使用andriodstudio 部署andiod项目

 腾讯SDK的安装方法 原文 地址http://android-mirror.bugly.qq.com:8080/include/usage.html ☀ Windows  I. Op...
  • lcg910978041
  • lcg910978041
  • 2016年09月17日 20:50
  • 1011

排序网络(Sorting network )构造的C语言实现

sorting network排序网络的定义可参考维基百科。其中,如何构造排序网络是一个很有意思的话题,一个基本的思想是递归的构造sorter来完成对2^k个输入的排序网络。这是我们算法设计这门课的一...
  • Meditator_hkx
  • Meditator_hkx
  • 2017年03月04日 15:08
  • 582

【内部排序】四:冒泡排序(Bubble Sorting)详解与代码

交换排序的基本思想:两两比较待排序记录的关键字,发现两个记录的次序相反时即进行交换,直到没有反序的记录为止。 两种交换排序:       (1)冒泡排序       (2)快速排序 一、冒泡排序...
  • zhoubin1992
  • zhoubin1992
  • 2015年04月20日 21:10
  • 1189

各位周末结束后都累了吧,那我们一起来看看【寒冬】的面试题吧(据说阿里的哟)

前言 虽然我CSS水平很水,但是水不是不学好的理由。 最近寒冬大哥针对面试发了一点“闹骚”,我们来看看他的微博是怎么说的呢? 面试的时候问个css的position属性能刷掉一半的人这是啥...
  • dyllove98
  • dyllove98
  • 2013年05月27日 19:22
  • 3110

经典排序算法 - 耐心排序Patience Sorting

经典排序算法 - 耐心排序Patience Sorting 这个排序的关键在建桶和入桶规则上 建桶规则:如果没有桶,新建一个桶;如果不符合入桶规则那么新建一个桶 入桶规则:只要比桶里最上边的数字...
  • u014723529
  • u014723529
  • 2014年12月16日 11:58
  • 1269
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Sorting ArrayList Containing User Defined Types
举报原因:
原因补充:

(最多只允许输入30个字)