In a sortedlist queue, queue.value[0] gives the corresponding value of a min key. what 开发者_JAVA技巧if i would like to make that it gives the value of a max key?
Do i have to rewrite the icomparer?
Yes you have to rewrite the comparer
example for string as key: (just exchanged x.CompareTo(y)
with y.CompareTo(x)
)
private class InvertedComparer : IComparer<String>
{
public int Compare(string x, string y)
{
return y.CompareTo(x);
}
}
and the call:
SortedList<string, Object> list = new SortedList<string, Object>(new InvertedComparer());
Here's a link to an article that implements a ReversibleSortedList
. This allows for changing the sort direction.
In case you always want reversed sort behavior without the ability to change it on demand, I'd try the constructor that accepts an IComparer.
Just use Array.Reverse()
in some simple cases.
using System;
class Program
{
static void Main()
{
// Input array.
int[] array = { 1, 2, 3 };
// Print.
foreach (int value in array)
{
Console.WriteLine(value);
}
Console.WriteLine();
// Reverse.
Array.Reverse(array);
// Print.
foreach (int value in array)
{
Console.WriteLine(value);
}
Console.WriteLine();
// Reverse again.
Array.Reverse(array);
// Print.
foreach (int value in array)
{
Console.WriteLine(value);
}
}
}
* Output *
1
2
3
3
2
1
1
2
3
You could just invert any existing IComparers. Something like:
public static IComparer<T> Invert<T>(this IComparer<T> comparer)
{
return Comparer<T>.Create((x, y) => comparer.Compare(y, x));
}
And use your regular comparer. For e.g.
new SortedList<,>(myShinyComparer.Invert());
精彩评论