Reverse Sorted Dictionary in .NET

后端 未结 5 444
广开言路
广开言路 2020-12-01 13:38

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

5条回答
  •  -上瘾入骨i
    2020-12-01 14:14

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

    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();
      
      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);
      }
      
    2. Make the dictionary sort in descending order.

      class DescendingComparer : IComparer where T : IComparable {
          public int Compare(T x, T y) {
              return y.CompareTo(x);
          }
      }
      
      // ...
      
      var Dict = new SortedDictionary(new DescendingComparer());
      
    3. Use SortedList 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();
    
    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]);
    }
    

提交回复
热议问题