C# .NET: Descending comparison of a SortedDictionary?

Posted by Rosarch on Stack Overflow See other posts from Stack Overflow or by Rosarch
Published on 2010-04-23T22:31:04Z Indexed on 2010/04/23 22:53 UTC
Read the original article Hit count: 394

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET