views:

65

answers:

1

I'm trying to place custom objects into a sorted dictionary... I am then trying to use an extension method (Max()) on this sorted dictionary. However, I'm getting the exception: "At least one object must implement IComparable". I don't understand why I'm getting that, 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 on earth am I doing wrong???

+1  A: 

That is because this is not trying to compare your custom objects, but instances of KeyValuePair.

This should work

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

Because the sorted dictionary is sorted, the last item is the largest assuming the comparer is comparing smallest to largest.

Chris Taylor
Chris, is calling .Last() or .First() an O(N) operation?? I wouldn't think it is, but I just want to be sure :)
Polaris878
@Polaris878, .Last() will be O(n) for SortedDictionary because it will enumerate all the elements using an in-order traversal of the tree to get to the last item. However if you have the dictionary sorted in reverse then you can use .First() which is O(log n) operation.
Chris Taylor