implement IComparable : IComparable « System « C# / C Sharp by API






implement IComparable


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

class Person : IComparable {
    public string Name;
    public int Age;

    public Person(string name, int age) {
        Name = name;
        Age = age;
    }

    public int CompareTo(object obj) {
        if (obj is Person) {
            Person otherPerson = obj as Person;
            return this.Age - otherPerson.Age;
        } else {
            throw new ArgumentException(
               "Object to compare to is not a Person object.");
        }
    }
}

class Program {
    static void Main(string[] args) {
        ArrayList list = new ArrayList();
        list.Add(new Person("A", 30));
        list.Add(new Person("B", 25));
        list.Add(new Person("B", 27));
        list.Add(new Person("E", 22));

        for (int i = 0; i < list.Count; i++) {
            Console.WriteLine("{0} ({1})",
               (list[i] as Person).Name, (list[i] as Person).Age);
        }
        list.Sort();
        for (int i = 0; i < list.Count; i++) {
            Console.WriteLine("{0} ({1})",
               (list[i] as Person).Name, (list[i] as Person).Age);
        }
    }
}

 








Related examples in the same category