C# .NET: Descending comparison of a SortedDictionary?
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 开发者_C百科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?
For descending order (largest values first), you would do -x.CompareTo(y)
try:
public int Compare(T x, T y)
{
return x.CompareTo(y);
}
In this line, switch x and y:
return -y.CompareTo(x);
Make it
return -x.CompareTo(y);
精彩评论