.NET 中的反向排序字典 [英] Reverse Sorted Dictionary in .NET

查看:24
本文介绍了.NET 中的反向排序字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以通过 c# 中的 SortedDictionary 向后(反向)迭代?

Is there any way I can iterate backwards (in reverse) through a SortedDictionary in c#?

或者有没有办法以降序定义SortedDictionary?

Or is there a way to define the SortedDictionary in descending order to begin with?

推荐答案

SortedDictionary 本身不支持向后迭代,但您有多种可能来实现相同的效果.

The SortedDictionary itself doesn't support backward iteration, but you have several possibilities to achieve the same effect.

  1. 使用 .Reverse-Method (Linq).(这将不得不预先计算整个字典的输出,但这是最简单的解决方案)

  1. 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>());
    

  • 使用 SortedList 代替.性能不如字典的 (O(n) 而不是 O(logn)),但您可以随机访问数组中的元素.当您使用通用 IDictionary-Interface 时,您无需更改其余代码.

  • 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.

    编辑 :: 在 SortedLists 上迭代

    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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆