SortedDictionary如何自訂排序

之前再寫資料檢索這堂課的作業時,碰到一個SortedDictionary排序上的問題,因為我在寫反轉索引法的過程中有使用到這個集合,其中Key的部分我是用來存放TF-IDF演算法求出來的weight score,這個值我是以double的型態來存放,不過因為SortedDictionary的排序方式是由小到大,也就是以升冪排序的方式幫你排序好了,但是我希望它能夠由大到小排序,因為作業的顯示結果要求weight score越高的結果要排越前面,所以我上MSDN查了一下SortedDictionary的資料後,本來看到它有一個Reverse的方法,不過後來研究了好久還是不會用,最後就上PTT的C_Sharp板去求助,經過Cloud大大的指導後終於解決這個問題了。


利用SortedDictionary建構式的一個多載,IComparer介面就可以實現自訂排序方式,來看看實作程式碼吧。

我們先看一下一開始SortedDictionary為我們排序的結果:
using System;
using System.Collections.Generic;
 
namespace SortedDictionarySample
{
class Program
{
static void Main(string[] args)
{
SortedDictionary<int, string> sortedDictionary = new SortedDictionary<int, string>();
 
sortedDictionary.Add(5, "五");
sortedDictionary.Add(4, "四");
sortedDictionary.Add(6, "六");
sortedDictionary.Add(2, "二");
sortedDictionary.Add(8, "八");
 
foreach (KeyValuePair<int, string> kvp in sortedDictionary)
Console.WriteLine(kvp.Value);
}
}
}



上面是一開始用SortedDictionary排序的結果,可以看出他是由小到大的升冪排序。
接下來就是本文的重點,自己定義SortedDictionary排序方式的實作方法:
using System;
using System.Collections.Generic;
 
namespace SortedDictionarySample
{
/// 
/// 遞減整數用的比較器,實作IComparer介面
/// 
public class IntegerDecreaseComparer : IComparer<int>
{
/// 
/// Compares two integer and returns a value indicating whether one is less than, equal to, or greater than the other.
/// 
/// The first integer to compare.
/// The second integer to compare. 
/// 
/// return Less than zero if x is less than y, 
/// return Zero if x equals y, 
/// return Greater than zero if x is greater than y.
/// 
public int Compare(int x, int y)
{
if (x < y)
return 1;
else
return -1;
}
}
 
class Program
{
static void Main(string[] args)
{
SortedDictionary<int, string> sortedDictionary = new SortedDictionary<int, string>(new IntegerDecreaseComparer());
 
sortedDictionary.Add(5, "五");
sortedDictionary.Add(4, "四");
sortedDictionary.Add(6, "六");
sortedDictionary.Add(2, "二");
sortedDictionary.Add(8, "八");
 
foreach (KeyValuePair<int, string> kvp in sortedDictionary)
Console.WriteLine(kvp.Value);
}
}
}

範例程式:
參考資料:

留言

這個網誌中的熱門文章

COSCUP 2012

Hahow 為什麼沒有 iOS App

swfobject - 網頁輕鬆嵌入Flash