Friday, September 25, 2009

Simple sample code using SortedList and IComparable in C#

Here is the simple code which uses SortedList and IComparable


Entity

class Test : IComparable<Test>    {
        int _order = 0;
        string _result = string.Empty;

        public int Order
        {
            get { return _order; }
            set{_order = value; }
        }
        public int CompareTo(Test t)
        {
            return _order.CompareTo(t.Order);
        }
        public string Result
        {
            get { return _result; }
            set { _result = value; }
        }
    }



Code to execute:


SortedList<Test, string> tests = new SortedList<Test, string>();
            Test t = new Test();
            t.Order = 10;
            t.Result = "1";
            tests.Add(t, "hello");
            t = new Test();
            t.Order = 5;
            t.Result = "2";
            tests.Add(t, "world");

            foreach (KeyValuePair<Test, string> kp in tests)
            {
                Console.WriteLine(kp.Key.Order);
            }

No comments:

Post a Comment