.Net IComparable example

using System;
using System.Collections.Generic;

namespace CsharpIComparableDemo
{
    class Program
    {
        static void Main()
        {
            var months = new List<Months>
                             {
                                 new Months() {Name = "January", Order = 1},
                                 new Months() {Name = "February", Order = 2},
                                 new Months() {Name = "March", Order = 3},
                                 new Months() {Name = "April", Order = 4},
                                 new Months() {Name = "May", Order = 5},
                                 new Months() {Name = "June", Order = 6},
                                 new Months() {Name = "July", Order = 7},
                                 new Months() {Name = "August", Order = 8},
                                 new Months() {Name = "September", Order = 9},
                                 new Months() {Name = "October", Order = 10},
                                 new Months() {Name = "November", Order = 11},
                                 new Months() {Name = "December", Order = 12}
                             };

            var monthsBare = new List<Months>
                             {
                                 new Months() {Name = "January"},
                                 new Months() {Name = "February"},
                                 new Months() {Name = "March"},
                                 new Months() {Name = "April"},
                                 new Months() {Name = "May"},
                                 new Months() {Name = "June"},
                                 new Months() {Name = "July"},
                                 new Months() {Name = "August"},
                                 new Months() {Name = "September"},
                                 new Months() {Name = "October"},
                                 new Months() {Name = "November"},
                                 new Months() {Name = "December"}
                             };

            months.Sort();

            months.ForEach(Print);

            Console.WriteLine();

            monthsBare.Sort();

            monthsBare.ForEach(Print);

            Console.ReadKey();
        }

        private static void Print(Months month)
        {
            Console.WriteLine("{0} {1}", month.Name, month.Order);
        }
    }

    public class Months : IComparable<Months>
    {
        public string Name { get; set; }
        public int Order { get; set; }

        public int CompareTo(Months month)
        {
            return Order == month.Order ? String.Compare(Name, month.Name, StringComparison.Ordinal) : month.Order.CompareTo(Order);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *