本文介绍了反向排序字典在.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 - 方法(LINQ)。 (这将有pre-计算整个字典输出,但是最简单的解决方案)

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

  • 使用排序列表&LT; TKEY的,TValue&GT; 代替。的表现并不好(而不是O(LOGN)为O(n))作为字典的,但你必须随机接入的像数组中的元素。当您使用通用的IDictionary接口,你不会有改变你的code中的其余部分。

  • 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 08-01 08:06