一般是对Hash标按key排序,但是我现在遇到的是需要按value排序,而且value可能多个是相同的,这里value是decimal类型的。
现在把我的代码跟大家分享,如果有更好的idea,尤其是我想把其中的比较器写成泛型,但是没成功。还请不吝赐教。
1。Comparer
//
// Abstract:
// Comparer for Hash Table (by Value)
public class HashComparerByValue : IComparer
{
private SortOrder sortDir = SortOrder.None;
public HashComparerByValue(SortOrder sd)
{
sortDir = sd;
}
public int Compare(object x, object y)
{
DictionaryEntry de_x = (DictionaryEntry)x;
DictionaryEntry de_y = (DictionaryEntry)y;
Decimal diff = (Decimal)de_x.Value - (Decimal)de_y.Value;
if (sortDir == SortOrder.Descending)
{
return (diff == 0) ? 0 : (diff > 0 ? -1 : 1);
}
else
{
return (diff == 0) ? 0 : (diff > 0 ? 1 : -1);
}
}
}
2。Comparision Function
private DictionaryEntry[] SortHashtable(Hashtable hasTbl, IComparer cmp)
{
DictionaryEntry[] dic = new DictionaryEntry[hasTbl.Count];
hasTbl.CopyTo(dic, 0);
Array.Sort(dic, cmp);
return dic;
}
3。Usage
......
DictionaryEntry[] dicEntry = new DictionaryEntry[scHash.Count];
HashComparerByValue hashCmp = new HashComparerByValue(SortOrder.Ascending);
dicEntry = SortHashtable(scHash, hashCmp);
foreach (DictionaryEntry scKey in dicEntry)
{
Console.WriteLine(scKey.Key.ToString());
}