add class objects in ArrayList and then sort them on the basis of a particular field

Posted by Ddd under C# category on | Points: 40 | Views : 2795
using System;
using System.Collections;

//we have to create an emp class and sort its objects in the ArrayList on the basis of empno field.

class emp
public int empno;
public string ename;
public emp(int a, string b)
empno = a;
ename = b;

public override string ToString()
return (empno + "----" + ename);



class abcd : IComparer

public int Compare(object ob1, object ob2)
emp a, b;
a = (emp)ob1;
b = (emp)ob2;
return a.empno.CompareTo(b.empno);

class Class4
static void Main()
abcd p = new abcd();

ArrayList t = new ArrayList();
t.Add(new emp(100, "king"));

t.Add(new emp(300, "james"));
t.Add(new emp(200, "jack"));

foreach (object y in t)




// 1) The sorting has been perfomed on the basis of empno field

// 2)abcd class implements the IComparer interface and its object has been passed in the Sort method

// of the ArrayList.

//3) Sort method will call the Compare method which does the Sorting by comparing all the objects of emp

// on the basis of empno's

//4) when the foreach loop is executed, overriding the ToString() method will display the eno and ename.

Comments or Responses

Login to post response