How to use IComparable in C#



This code snippet shows how to implement IComparable in C#.

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;
            }
        }
        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;
        }
        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());
            }

        }
    }
}
 


Similar Articles