[英]Sorting SortedList in descending order C#
我有
SortedList<string, object> testIds = new SortedList<string, object>();
我把它按降序排列。 我用於排序下一個結構:
testIds.ToList().Sort(delegate(KeyValuePair<string, object>x, KeyValuePair<string, object>y)
{
return x.Key.CompareTo(y.Key)*-1;
});
但它沒有幫助我。你能給我一些建議如何解決這個問題?
盡管SortedList<K,V>
默認按升序排序,但它提供了一個構造函數,該構造函數采用自定義IComparer<K>
,可讓您將訂單切換到您需要的任何內容。
實現IComparer<string>
,它反轉常規比較的結果,並將其提供給SortedList<K,V>
的構造函數:
class ReverseComparer : IComparer<string> {
public int Compare(string x, string y) {
return -x.CompareTo(y);
}
}
var testIds = new SortedList<string,object>(new ReverseComparer());
您可以在一行中編寫相同的內容,而無需為其創建命名類:
var testIds = new SortedList<string,object>(
// Note how the negation is replaced with reversing the order of comparison
Comparer<string>.Create((x, y) => y.CompareTo(x))
);
正如dasblinkenlight所指出的,你應該使用帶有IComparer<T>
的構造函數重載。
但是,如果這是一次性的事情,那么最好使用Comparer<T>.Create
,而不是僅為此創建一個全新的類。
var comparer = Comparer<string>.Create((x, y) => y.CompareTo(x));
var testIds = new SortedList<string,object>(comparer);
此外,當以相反順序比較項目時,慣例是將y
與x
進行比較,而不是將x
與y
進行比較並反轉結果。
只需使用Reverse。 假設你有一個有序列表OrigOrderedList,那么
SortedList<string, object> testIds = OrigOrderedList.Reverse() // should do the work
static void Main(string[] args)
{
SortedList<string, object> test1 = new SortedList<string, object>();
test1.Add("a", "A");
test1.Add("b", "B");
test1.Add("c", "C");
Console.WriteLine(String.Join(", ", test1.Select(x => x.Key)));
Console.WriteLine(String.Join(", ", test1.Reverse().Select(x => x.Key)));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.