Getting an exception when trying to use an extension method with a SortedDictionary ... why?

I am trying to put custom objects in a sorted dictionary ... Then I am trying to use the extension method (Max ()) on this sorted dictionary. However, I get an exception: "At least one object must implement IComparable". I don't understand why I am getting this as my custom object obviously implements IComparable. Here is my code:

public class MyDate : IComparable<MyDate>
{
    int IComparable<MyDate>.CompareTo(MyDate obj)
    {
        if (obj != null)
        {
            if (this.Value.Ticks < obj.Value.Ticks)
            {
                return 1;
            }
            else if (this.Value.Ticks == obj.Value.Ticks)
            {
                return 0;
            }
            else
            {
                return -1;
            }
        }
    }

    public MyDate(DateTime date)
    {
        this.Value = date;
    }

    public DateTime Value;
}


class Program
{
    static void Main(string[] args)
    {
        SortedDictionary<MyDate, int> sd = new SortedDictionary<MyDate,int>();

        sd.Add(new MyDate(new DateTime(1)), 1);
        sd.Add(new MyDate(new DateTime(2)), 2);

       Console.WriteLine(sd.Max().Value);   // Throws exception!!  
    }
}

      

What am I doing wrong?

+2


a source to share


1 answer


This is because it doesn't try to compare your custom objects, but the KeyValuePair instances.

This should work



Console.WriteLine(sd.Last().Value);   

      

Since the sorted dictionary is sorted, the last element is the largest, assuming the comparator is comparing smallest to largest.

+1


a source







All Articles