.NET中的反向排序字典 [英] Reverse Sorted Dictionary in .NET
问题描述
有没有办法通过C#中的SortedDictionary反向(反过来)或者有一种方式可以按降序定义SortedDictionary,以便开始用?
SortedDictionary本身不支持向后迭代,但您有几种可能性来实现相同的效果。
-
使用
.Reverse
-Method(Linq)。 (这将必须预先计算整个字典输出,但是是最简单的解决方案)var Rand = new Random();
var Dict = new SortedDictionary< int,string>(); (int i = 1; i< = 10; ++ i){
var newItem = Rand.Next(1,100);
Dict.Add(newItem,(newItem * newItem).ToString());
}
foreach(Dict.Reverse()中的var x){
Console.WriteLine({0} - > {1},x.Key,x 。值);
}
-
使字典按降序排列。
class DescendingComparer< T> :IComparer< T>其中T:IComparable< T> {
public int Compare(T x,T y){
return y.CompareTo(x);
}
}
// ...
var Dict = new SortedDictionary< int,string>(new DescendingComparer< int>()) ;
-
使用
SortedList< TKey,TValue>
而不是。性能不如字典(O(n)而不是O(logn)),但是您可以在数组中的元素进行随机访问。当您使用通用IDictionary-Interface时,您不必更改其余的代码。
:迭代排序列表
您只需通过索引访问元素!
var Rand = new Random();
var Dict = new SortedList< int,string>(); (int i = 1; i< = 10; ++ i){
var newItem = Rand.Next(1,100);
Dict.Add(newItem,(newItem * newItem).ToString());
}
//反向循环(forr + tab)
for(int i = Dict.Count - 1; i> = 0; --i){
Console.WriteLine({0} - > {1},Dict.Keys [i],Dict.Values [i]);
}
Is there any way I can iterate backwards (in reverse) through a SortedDictionary in c#?
Or is there a way to define the SortedDictionary in descending order to begin with?
The SortedDictionary itself doesn't support backward iteration, but you have several possibilities to achieve the same effect.
Use
.Reverse
-Method (Linq). (This will have to pre-compute the whole dictionary output but is the simplest solution)var Rand = new Random(); var Dict = new SortedDictionary<int, string>(); for (int i = 1; i <= 10; ++i) { var newItem = Rand.Next(1, 100); Dict.Add(newItem, (newItem * newItem).ToString()); } foreach (var x in Dict.Reverse()) { Console.WriteLine("{0} -> {1}", x.Key, x.Value); }
Make the dictionary sort in descending order.
class DescendingComparer<T> : IComparer<T> where T : IComparable<T> { public int Compare(T x, T y) { return y.CompareTo(x); } } // ... var Dict = new SortedDictionary<int, string>(new DescendingComparer<int>());
Use
SortedList<TKey, TValue>
instead. The performance is not as good as the dictionary's (O(n) instead of O(logn)), but you have random-access at the elements like in arrays. When you use the generic IDictionary-Interface, you won't have to change the rest of your code.
Edit :: Iterating on SortedLists
You just access the elements by index!
var Rand = new Random();
var Dict = new SortedList<int, string>();
for (int i = 1; i <= 10; ++i) {
var newItem = Rand.Next(1, 100);
Dict.Add(newItem, (newItem * newItem).ToString());
}
// Reverse for loop (forr + tab)
for (int i = Dict.Count - 1; i >= 0; --i) {
Console.WriteLine("{0} -> {1}", Dict.Keys[i], Dict.Values[i]);
}
这篇关于.NET中的反向排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!