Thursday, April 26, 2012

C# Sort dictionary containing objects

Hi After searching a lot over internet how to sort dictionary containing objects e.g Dictionary<string,myclass> I end up writing this simple but effective method please have a look .



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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, delta> mydict = new Dictionary<string, delta>();
            mydict.Add("a", new delta(true, 3,"ash1"));
            mydict.Add("d", new delta(false, 1,"bsh2"));
            mydict.Add("e", new delta(false, 1 , "ash3"));
            mydict.Add("b", new delta(true, 2 , "ash4"));
            IComparer<delta> myComparerorder = new compareorder() as IComparer<delta>;
            IComparer<delta> myComparerbool = new comparebool() as IComparer<delta>;
            IComparer<delta> myComparerstring = new comparestring() as IComparer<delta>;
            var sortedDict = mydict.OrderByDescending(x => (delta)x.Value, myComparerbool).ThenBy(x => (delta)x.Value, myComparerorder).ThenBy(x=>(delta)x.Value , myComparerstring);


            foreach (var key in sortedDict)
            {
                var _key = key.Key;
                var _delta = mydict[_key];
                Console.WriteLine(_delta.order + "---" + _delta.global + "----" + _delta.name);
            }
        }
    }
    public class delta
    {
        public bool global;
        public int order;
        public string name;
        public delta(bool _global,int _order,string _name)
        {


            global = _global;
            order = _order;
            name = _name;
        }
    }


    public class compareorder : IComparer<delta>
    {
        public int Compare(delta x, delta y)
        {
            if (x.order > y.order)
                return 1;
            if (x.order < y.order)
                return -1;
            else
                return 0;
        }
    }


    public class comparebool : IComparer<delta>
    {


        public int Compare(delta x, delta y)
        {
            return x.global.CompareTo(y.global);
        }
    }


    public class comparestring : IComparer<delta>
    {


        public int Compare(delta x, delta y)
        {
            return x.name.CompareTo(y.name);
        }
    }




}




The output of the above code will be:---


2---True----ash4
3---True----ash1
1---False----ash3
1---False----bsh2









No comments: