Wednesday, 23 May 2012

IComparable Interface in c#

Sort by Price list;

Step 1)  Create console Application
Step 2) Add class called Stocks.cs  and implement IComparable interface

fileName: Stocks.cs

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


/// <summary>
/// Summary description for Stocks
/// </summary>
public class Stocks : IComparable
{
    public String Symbol;
    public decimal price;
    public DateTime dtPrice;

    public int CompareTo(object obj)
    {
        if (obj == null) return 1;
        Stocks st = obj as Stocks;
        return this.price.CompareTo(st.price);
    }
}

Step 3)  in Program.cs
             1)  Initialize array of objects(i.e stocks)
              2) display without sorting
             3) display after sorting

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Stocks[] stockList =
    {
        new Stocks{Symbol="IBM", price=88.80M, dtPrice=new System.DateTime(2012,6,26,9,00,00)},
        new Stocks{Symbol="CSCO", price=22.80M, dtPrice=new System.DateTime(2012,6,26,9,00,00)},
        new Stocks{Symbol="INTL", price=32.80M, dtPrice=new System.DateTime(2012,6,26,9,00,00)},
 
    };

            Console.WriteLine("Before Sort ......");
            foreach (Stocks s in stockList)
            {
                Console.Write("Symbol={0},rate={1},date={2}",s.Symbol,s.price,s.dtPrice);
                Console.WriteLine();

            }

            Array.Sort(stockList); //sort arrays ,icomparable compare function will be called.

            Console.WriteLine("After Sort ......");
            foreach (Stocks s in stockList)
            {
                Console.Write("Symbol={0},rate={1},date={2}", s.Symbol, s.price, s.dtPrice);
                Console.WriteLine();

            }


        }
    }
}



OUTPUT