Arrao4u

…a blog by Rama Rao

Archive for the ‘ArrayList’ Category

ArrayList sorting

Posted by arrao4u on December 12, 2009

You can easily sort an arraylist using its “sort()” method, but how can you sort an ArrayList of Objects? You can get this task done very easily with “IComparer” Interface.

As an example let’s get a “Person” object which contains two attributes called “ID” and “Name”. Now we need to sort these objects by “ID” or “Name”. By looking at the following picture, you can get very clear idea about what we are going to do now.

You may notice in “Sort 2” first I have sort by “ID” and then by “Name”. I’ll give you the C# code for the above task using simple console application.

Create new class called “Person” and paste this code;

01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05
06 namespace SortArrayList
07 {
08 class Person
09 {
10 private int id;
11 public int ID
12 {
13 get { return id; }
14 set { id = value; }
15 }
16 private string name;
17 public string Name
18 {
19 get { return name; }
20 set { name = value; }
21 }
22 public int CompareTo(Person psn2, ObjCompare.ComparisonType comparisonType, Person psn1)
23 {
24 int returnValue;
25 if (comparisonType == ObjCompare.ComparisonType.ID)
26 {
27 if (psn1.ID == psn2.ID)
28 {
29 returnValue = Name.CompareTo(psn2.Name);
30 }
31 else
32 {
33 returnValue = ID.CompareTo(psn2.ID);
34 }
35 }
36 else if (comparisonType == ObjCompare.ComparisonType.Name)
37 {
38 returnValue = Name.CompareTo(psn2.Name);
39 }
40 else
41 {
42 returnValue = ID.CompareTo(psn2.ID);
43 }
44 return returnValue;
45 }
46 }
47 }

Create new class called “ObjCompare” and paste this code;

01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05 using System.Collections;
06
07 namespace SortArrayList
08 {
09 class ObjCompare : IComparer
10 {
11 public enum ComparisonType
12 {
13 ID, Name
14 }
15 private ComparisonType compMethod;
16 public ComparisonType ComparisonMethod
17 {
18 get { return compMethod; }
19 set { compMethod = value; }
20 }
21 public int Compare(object x, object y)
22 {
23 Person psn1 = (Person)x;
24 Person psn2 = (Person)y;
25 return psn1.CompareTo(psn2, ComparisonMethod, psn1);
26 }
27 }
28 }

Now update your “Programme.cs” as bellow;

01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05 using System.Collections;
06
07 namespace SortArrayList
08 {
09 class Program
10 {
11 static void Main(string[] args)
12 {
13 ArrayList lst = new ArrayList();
14
15 Person psn = new Person();
16 psn.Name = "Jack"; psn.ID = 15;
17 lst.Add(psn);
18
19 Person psn1 = new Person();
20 psn1.Name = "David"; psn1.ID = 18;
21 lst.Add(psn1);
22
23 Person psn2 = new Person();
24 psn2.Name = "Daniel"; psn2.ID = 12;
25 lst.Add(psn2);
26
27 Person psn3 = new Person();
28 psn3.Name = "Owen"; psn3.ID = 20;
29 lst.Add(psn3);
30
31 Person psn4 = new Person();
32 psn4.Name = "Colin"; psn4.ID = 16;
33 lst.Add(psn4);
34
35 Person psn5 = new Person();
36 psn5.Name = "Aiden"; psn5.ID = 18;
37 lst.Add(psn5);
38
39 Console.Write(" ---before sort --- \n");
40 foreach (Person item in lst)
41 {
42 int id = item.ID;
43 string ttl = item.Name;
44 Console.Write(id + " " + ttl + "\n");
45 }
46 /* sorting */
47 ObjCompare objcom = new ObjCompare();
48 objcom.ComparisonMethod = ObjCompare.ComparisonType.ID;
49 lst.Sort(objcom);
50
51 Console.Write(" ---after sort -- \n");
52 foreach (Person item in lst)
53 {
54 int id = item.ID;
55 string ttl = item.Name;
56 Console.Write(id + " " + ttl + "\n");
57 }
58 }
59 }
60 }

You will get the output as “Sort 2” in the picture. If you don’t want to sort by “Name” you can do it by editing “Person” class. There I have check whether “psn1.ID == psn2.ID”, by commenting that part you can get the result as “Sort 1”.

ref:http://sarangasl.blogspot.com/2009/10/sort-object-arraylist-in-c.html

I can sort an ArrayList of Strings.  How can I sort an ArrayList of Objects?  Can it be done?  Yes, you can do it with IComparable.  I know some are so enthused about Generics, they have made statements like, “I will never use an ArrayList again.”  But ArrayLists are still very powerful and have their place.  This application will show you why.

This week I am working on an application that has to sort a relatively small number of Input Lines (300 or so) on Social Security Number because there can be multiple lines of input for the same person.  The application makes a call to a Web Service for each person but should only make one call per person.  The processing of the application requires that I build objects prior to beginning the processing.  Since the input file can have multiple lines for the same person, the objects must be sorted.

Even if the first Property of the data class is the SSN, you cannot just place the objects in an ArrayList and then sort the ArrayList.  Your class must Implement IComparable and you must creat an IComparable.CompareTo function in the class.  This article will show you the code for a Console Application in both C# and VB.NET to accomplish the sorting.

Figure 1 – C# Sorting ArrayList of Objects.

using System;
using System.Collections;
namespace SortArrayListOfObjects
{
class Class1
{
static ArrayList al = new ArrayList();
[STAThread]
static void Main(string[] args)
{
BuildArrayList();
ListSortedObjects(); //list data before sorting
al.Sort();
ListSortedObjects();
Console.ReadLine();
}

static private void BuildArrayList()
{
MyObject obj1 = new MyObject();
obj1.EmpID = 1;
obj1.SSN = “234567890”;
obj1.Name = “Les Smith”;
al.Add(obj1);
MyObject obj2 = new MyObject();
obj2.EmpID = 2;
obj2.SSN = “987654321”;
obj2.Name = “Bob Jones”;
al.Add(obj2);
MyObject obj3 = new MyObject();
obj3.EmpID = 3;
obj3.SSN = “123456789”;
obj3.Name = “Jim Jones”;
al.Add(obj3);
}

static private void ListSortedObjects()
{
foreach (MyObject obj in al)
{
Console.WriteLine(obj.SSN);
Console.WriteLine(obj.EmpID.ToString());
Console.WriteLine(obj.Name);
}
}
}

public class MyObject : IComparable
{
public string SSN;
public int EmpID;
public string Name;

public int CompareTo(object obj)
{
MyObject Compare = (MyObject)obj;
int result = this.SSN.CompareTo(Compare.SSN);
if (result == 0)
result = this.SSN.CompareTo(Compare.SSN);
return result;
}
}
}

The application is stright-forward and does not need much explanation.  Since the ArrayList does not have the capability to sort objects as it would strings, I had to Implement an IComparable.CompareTo function to facilitate the sort.  Obviously, you can expand or modify the CompareTo function to sort on multiple properties of different types.

Figure 2 – VB.NET Sorting ArrayList of Objects.

Imports System
Imports System.Collections
Module Module1

Private al As New ArrayList
Sub Main()
BuildArrayList()
ListSortedObjects()
al.Sort()
ListSortedObjects()
Console.ReadLine()
End Sub

Private Sub BuildArrayList()
Dim obj1 As MyObject = New MyObject
obj1.EmpID = 1
obj1.SSN = “234567890”
obj1.Name = “Les Smith”
al.Add(obj1)
Dim obj2 As MyObject = New MyObject
obj2.EmpID = 2
obj2.SSN = “987654321”
obj2.Name = “Bob Jones”
al.Add(obj2)
Dim obj3 As MyObject = New MyObject
obj3.EmpID = 3
obj3.SSN = “123456789”
obj3.Name = “Jim Jones”
al.Add(obj3)
End Sub

Private Sub ListSortedObjects()
Dim obj As MyObject
For Each obj In al
Console.WriteLine(obj.SSN)
Console.WriteLine(obj.EmpID.ToString())
Console.WriteLine(obj.Name)
Next
End Sub

End Module
Public Class MyObject
Implements IComparable
Public SSN As String
Public EmpID As Integer
Public Name As String

Public Function CompareTo(ByVal obj As Object) As Integer _
Implements System.IComparable.CompareTo
If Not TypeOf obj Is MyObject Then
Throw New Exception(“Object is not MyObject”)
End If
Dim Compare As MyObject = CType(obj, MyObject)
Dim result As Integer = Me.SSN.CompareTo(Compare.SSN)

If result = 0 Then
result = Me.SSN.CompareTo(Compare.SSN)
End If
Return result
End Function
End Class

The code for C# and VB.NET is almost identical except for the differing of the syntax of the two languages.

The following lines show the contents of the ArrayList before it is sorted.

234567890
1
Les Smith
987654321
2
Bob Jones
123456789
3
Jim Jones

The following output shows the contents of the ArrayList after it is sorted.

123456789
3
Jim Jones
234567890
1
Les Smith
987654321
2
Bob Jones

ref:http://www.knowdotnet.com/articles/sortarraylistofobjects.html

This article explains you how to customize sorting in ArrayList in C#. In this example I have put together a simple class called Category. A Category object one contains two member variables, one is Category Type and Category Type code.

Code snippet:

using System;

namespace ArrayListSORTING 
{
	public class Category 
	{
		public string Type;
		public int TypeCode;

		public Category() 
		{
		}

		public Category(string type, int tcode) 
		{
			this.Type = type;
			this.TypeCode = tcode;
		}
	}
}

Business logic For Sorting

Our comparer is called CategoryComparer, and we also have an enum called SortDirection which allows us to define whether we want to sort in an Ascending or in Descending order.

using System;
using System.Collections;

namespace ArrayListSORTING 
{

	public enum SortDirection 
	{
		Asc,
		Desc
	}

	public class CategoryComparer : IComparer 
	{

		private SortDirection m_direction = SortDirection.Asc;

		public CategoryComparer() : base() { }

		public CategoryComparer(SortDirection direction) 
		{
			this.m_direction = direction;
		}

		int IComparer.Compare(object x, object y) 
		{

			Category categoryX = (Category) x;
			Category categoryY = (Category) y;

			if (categoryX == null && categoryY == null) 
			{
				return 0;
			} 
			else if (categoryX == null && categoryY != null) 
			{
				return (this.m_direction == SortDirection.Asc) ? -1 : 1;
			} 
			else if (categoryX != null && categoryY == null) 
			{
				return (this.m_direction == SortDirection.Asc) ? 1 : -1;
			} 
			else 
			{
				return (this.m_direction == SortDirection.Asc) ?
					categoryX.TypeCode.CompareTo(categoryY.TypeCode) : 
					categoryY.TypeCode.CompareTo(categoryX.TypeCode);
			}
		}
	}
}

Testing With Sample Code

For testing our sample we need to create a new arraylist and we have to add some items in that arraylist and test it.

using System;
using System.Collections;

namespace ArrayListSORTING 
{

	class SortArrayList 
	{

		[STAThread]
		static void Main(string[] args) 
		{

			ArrayList list = new ArrayList();

			list.Add(new Category("Music", 4));
			list.Add(new Category("Play", 7));
			list.Add(new Category("Dance", 2));
			list.Add(new Category("Party", 9));
			list.Add(new Category("Disco", 1));
			list.Add(new Category("Sport", 3));

			list.Sort(new CategoryComparer());

			Console.WriteLine("Array in Ascending Order");
			foreach (Category cate in list) 
			{
				Console.WriteLine("CategoryName: " + cate.Type + ", CategoryCode: " + cate.TypeCode.ToString());
			}

			list.Sort(new CategoryComparer(SortDirection.Desc));

			Console.WriteLine("\n\rArray in Desending Order");
			foreach (Category cate in list) 
			{
				Console.WriteLine("CategoryName: " + cate.Type + ", CategoryCode: " + cate.TypeCode.ToString());
			}
			Console.ReadLine();
		}
	}
}

ref:http://www.dotnetspider.com/resources/1323-How-Sort-ArrayList-Using-C.aspx

Posted in ArrayList, C#, Collections | Leave a Comment »