Blog

Array sorting

Posted by Awadhesh Singh Blogs | .NET 4.5 Nov 14, 2012
Array sorting in C#.
using System;
using System.Collections;

namespace ArrayListSORTING
{
    public enum SortDirection
    {
        Asc,
        Desc
    }
    public class CategoryComparer : IComparer
    {
        private SortDirection m_direction = SortDirection.Asc;
        public CategoryComparer() : base() { }
        public CategoryComparer(SortDirection direction)
        {
            this.m_direction = direction;
        }
        int IComparer.Compare(object x, object y)
        {
            Category categoryX = (Category) x;
            Category categoryY = (Category) y;
            if (categoryX == null && categoryY == null)
            {
                return 0;
            }
            else if (categoryX == null && categoryY != null)
            {
                return (this.m_direction == SortDirection.Asc) ? -1 : 1;
             }
             else if (categoryX != null && categoryY == null)
             {
                 return (this.m_direction == SortDirection.Asc) ? 1 : -1;
             }
             else
             {
                 return (this.m_direction == SortDirection.Asc) ?
                 yX.TypeCode.CompareTo(categoryY.TypeCode) :
                 categoryY.TypeCode.CompareTo(categoryX.TypeCode);
            }
        }
    }
}
 
using System;
using System.Collections;

namespace ArrayListSORTING
{
    class SortArrayList
    {
        [STAThread]
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add(new Category("Music", 4));
            list.Add(new Category("Play", 7));
            list.Add(new Category("Dance", 2));
            list.Add(new Category("Party", 9));
            list.Add(new Category("Disco", 1));
            list.Add(new Category("Sport", 3));
            list.Sort(new CategoryComparer());
            Console.WriteLine("Array in Ascending Order");
            foreach (Category cate in list)
            {
                Console.WriteLine("CategoryName: " + cate.Type + ", CategoryCode: " + cate.TypeCode.ToString());
            }
                list.Sort(new CategoryComparer(SortDirection.Desc));
                Console.WriteLine("\n\rArray in Desending Order");
                foreach (Category cate in list)
                {
                    Console.WriteLine("CategoryName: " + cate.Type + ", CategoryCode: " + cate.TypeCode.ToString());
                 }
                Console.ReadLine();
        }
    }
}
post comment
     
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter