SortedDictionary 如何自訂排序
之前再寫 資料檢索這堂課的作業時,碰到一個 SortedDictionary 排序上的問題,因為我在寫 反轉索引法的過程中有使用到這個集合,其中 Key 的部分我是用來存放 TF-IDF 演算法求出來的 weight score,這個值我是以 double…
之前再寫 資料檢索這堂課的作業時,碰到一個 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); } }}範例程式:
參考資料: