有什么方法可以在 C# 中向后(反向)迭代 SortedDictionary 吗?
或者有没有办法首先按降序定义 SortedDictionary ?
SortedDictionary 本身不支持向后迭代,但您有多种可能性来实现相同的效果。
-
Use .Reverse
-方法(Linq)。 (这必须预先计算整个字典输出,但这是最简单的解决方案)
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);
}
-
使字典按降序排序。
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>
反而。性能不如字典(O(n) 而不是 O(logn)),但您可以像数组一样随机访问元素。当您使用通用 IDictionary-Interface 时,您无需更改其余代码。
编辑::迭代SortedLists
您只需通过索引访问元素即可!
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]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)