Sorting arraylist containing user defined Types

xiaoxiao2021-03-06  90

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 what, but note what those will be complex type, whch mean this, what is the the parameter you are going to use to sort your ing 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 what containing your defined type, and this type do not import 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 THISTANCE IS LESS THAN OBJ. ZERO IF THISTANCE IS Equal To Obj. Greater Than Zero if this instance is get tour..

SO All we have to do when building Our ing type is to ustement 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_EMPSALY;

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 Salry

{

Get {return m_empsalary;

Set {m_empsalary = value;

}

///

/// Less Than Zero if this instance is less Obj.

/// Zero if this instance is equal to obj.

/// Greater Than Zero if this instance is greater tour.

///

///

/// 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 shutrite the code again, we have int.compareto ready to us

Return this.id.comPareto (Emp.ID);

}

}

As you see in that class, it is easy to implement the IComparable interface. And also I did not 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

Else if (this.id == Emp.ID)

Return 0;

Else

Return 1;

That was easy was not 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;

}

}

转载请注明原文地址:https://www.9cbs.com/read-123841.html

New Post(0)