views:

226

answers:

3

I'm want a IDictionary<float, foo> that returns the larges values of the key first.

private IDictionary<float, foo> layers = new SortedDictionary<float, foo>(new DescendingComparer<float>());

class DescendingComparer<T> : IComparer<T> where T : IComparable<T>
{
    public int Compare(T x, T y)
    {
        return -y.CompareTo(x);
    }
}

However, this returns values in order of the smallest first. I feel like I'm making a stupid mistake here.

Just to see what would happen, I removed the - sign from the comparator:

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

But I got the same result. This reinforces my intuition that I'm making a stupid error.

This is the code that accesses the dictionary:

foreach (KeyValuePair<float, foo> kv in sortedLayers)
{
    // ...
}

UPDATE: This works, but is too slow to call as frequently as I need to call this method:

IOrderedEnumerable<KeyValuePair<float, foo>> sortedLayers = layers.OrderByDescending(kv => kv.Key);
foreach (KeyValuePair<float, ICollection<IGameObjectController>> kv in sortedLayers) { 
    // ...
}

UPDATE: I put a break point in the comparator that never gets hit as I add and remove kv pairs from the dictionary. What could this mean?

A: 

try:

public int Compare(T x, T y)
{
    return x.CompareTo(y);
}
derek
That still doesn't do it. hmm..
Rosarch
+1  A: 

For descending order (largest values first), you would do -x.CompareTo(y)

Michael Petito
This doesn't work, but I feel like it should. Perhaps I'm doing something else wrong.
Rosarch
@Rosarch: It definitely should work, I know I've used it before. If you debug your code, do you find that your Compare method is actually called?
Michael Petito
Looks like it isn't, actually. Am I creating the `SortedDictionary` incorrectly?
Rosarch
@Rosarch: No, you are creating the dictionary correctly. Check to make sure that you are using the same dictionary you've constructed above later on in your code when adding/removing elements and enumerating. IE. Find all references to `layers` and make sure there isn't another piece of code assigning a different `SortedDictionary`.
Michael Petito
A: 

In this line, switch x and y:

return -y.CompareTo(x);

Make it

return -x.CompareTo(y);
Jacob O'Reilly