Sorting ArrayList Containing User Defined Types

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

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值