Saturday, July 3, 2010

IComparable and IComparer

this example is about how to implement IComparable and IComparer interface,
so you can Sort your class members Ascending or Descending

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication5
{


class data : IComparable
{
string name;
int age;

public data()
{

}
public data(string name, int age)
{

this.name = name;
this.age = age;
}

public string _name
{
get
{
return name;
}
}
public int _age
{
get
{
return age;
}
}
///////////////////use IComparable and CompareTo method
///////////////////to sort the members Descending
public int CompareTo(object obj)
{
data m = (data)obj;
if (m._age < this._age)
return 1;
else if (m._age > this._age)
return -1;
else
return 0;
}
//////////////use IComparer and Compare method
//////////////to sort the members Descending
public class sortDes : IComparer
{

int IComparer.Compare(object x, object y)
{
data m = (data)x;
data n = (data)y;
if (m._age < n._age)
return 1;
else if (m._age > n._age)
return -1;
else
return 0;
}

}


}

class Program
{
static void Main(string[] args)
{
data[] x = new data[4];
x[0] = new data("Ali", 10);
x[1] = new data("mohammed", 24);
x[2] = new data("wael", 3);
x[3] = new data("slah", 34);
// Array.Sort(x) //for will sort it Ascending
Array.Sort(x, new data.sortDes());
foreach (data d in x)
{
Console.WriteLine(d._name + " " + d._age.ToString());
}


}
}
}

No comments:

Post a Comment