SIGN UP MEMBER LOGIN:    
ARTICLE

Implementing an IComparable interface to a Class

Posted by Amit Choudhary Articles | C# Language March 31, 2010
Here I have given an example of how to sort an Person class on the basis of its attribute by implementing IComparable interface.
Reader Level:
Download Files:
 

Many time we need to use sorting with our objects of custom classes.

Here I have given an example of how to sort an Person class on the basis of its attribute by implementing IComparable interface.

using
System;

//Add refrence to Collections namespace

using
System.Collections;

class
Inventory : IComparable
{
    string name;
    double cost;
    int onhand;

    public Inventory(string n, double c, int h)
    {
        name = n;
        cost = c;
        onhand = h;
    }

  
//Overriding the ToString() method to show the output formatted
    public override string ToString()
    {
       
return
        String.Format("{0,-10}Cost: {1,6:C}  On hand: {2}", name, cost, onhand);
    }

   
// Implement the IComparable interface.
    public int CompareTo(object obj)
    {
        Inventory b;
        b = (Inventory)obj;
        return name.CompareTo(b.name);
    }
}


public
class IComparableDemo
{
    public static void Main()
    {
        ArrayList inv = new ArrayList();

       
// Add elements to the list
        inv.Add(new Inventory("Pliers", 5.95, 3));
        inv.Add(new Inventory("Wrenches", 8.29, 2));
        inv.Add(new Inventory("Hammers", 3.50, 4));
        inv.Add(new Inventory("Drills", 19.88, 8));
        Console.WriteLine("Inventory list before sorting:");

        foreach (Inventory i in inv)
        {
            Console.WriteLine("   " + i);
        }
        Console.WriteLine();

       
// Sort the list.
        inv.Sort();
        Console.WriteLine("Inventory list after sorting:");

        foreach (Inventory i in inv)
        {
            Console.WriteLine("   " + i);
        }
    }
}


Happy coding.

Cheers.

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Gauge for SharePoint
Become a Sponsor