Navigation

Search

Categories

On this page

How to Sort ArrayList with ICompare Interface

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 291
This Year: 0
This Month: 0
This Week: 0
Comments: 0

Sign In
Pick a theme:

# Saturday, April 19, 2008
Saturday, April 19, 2008 9:33:32 AM (GTB Daylight Time, UTC+03:00) ( C# )

A simple demostration shows how to sort an ArrayList in C#.

Output of the program will be:

Printing List before sorting:

1 = 2,5

2 = 1,9

3 = 4

4 = 10,5

5 = 1,1

6 = 3,5

 

Printing List in ascending order

5 = 1,1

2 = 1,9

1 = 2,5

6 = 3,5

3 = 4

4 = 10,5

 

C Sharp Code

using System;

using System.Collections.Generic;

using System.Collections;

 

namespace ArrayListSort

{

class Program

{

static void Main(string[] args)

{

ArrayList List = new ArrayList();

 

List.Add( new Item(1,2.5) );

List.Add(new Item(2, 1.9));

List.Add(new Item(3, 4.0));

List.Add(new Item(4, 10.5));

List.Add(new Item(5, 1.1));

List.Add(new Item(6, 3.5));

 

Console.WriteLine("Printing List before sorting:");

for (int i = 0; i < List.Count; i++)

{

Item D = (Item)List[i];

Console.WriteLine(D.Id + " = " + D.Difference);

}

 

List.Sort();

 

Console.WriteLine("\nPrinting List in ascending order");

for (int i = 0; i < List.Count; i++)

{

Item D = (Item)List[i];

Console.WriteLine( D.Id + " = " + D.Difference );

}

Console.ReadLine();

 

}

}

 

class Item : IComparable

{

 

#region Members

private int mId;

 

public int Id

{

get { return mId; }

set { mId = value; }

}

 

private double mDifference;

 

public double Difference

{

get { return mDifference; }

set { mDifference = value; }

}

#endregion Members

 

#region Constructor

public Item(int _id, double _diff)

{

this.mDifference = _diff;

this.mId = _id;

}

#endregion Constructor

 

#region Compare Interface

public Int32 CompareTo(Object _item)

{

Item ItemInstance = (Item)_item;

 

if (this.Difference > ItemInstance.Difference)

{

return 1;

}

else

{

return -1;

}

 

}

#endregion Compare Interface

 

 

}

}