Reverse Sorted Dictionary in .NET

后端 未结 5 450
广开言路
广开言路 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条回答
  •  伪装坚强ぢ
    2020-12-01 14:24

    The easiest way to define the SortedDictionary in the reverse order to start with is to provide it with an IComparer which sorts in the reverse order to normal.

    Here's some code from MiscUtil which might make that easier for you:

    using System.Collections.Generic;
    
    namespace MiscUtil.Collections
    {
        /// 
        /// Implementation of IComparer{T} based on another one;
        /// this simply reverses the original comparison.
        /// 
        /// 
        public sealed class ReverseComparer : IComparer
        {
            readonly IComparer originalComparer;
    
            /// 
            /// Returns the original comparer; this can be useful
            /// to avoid multiple reversals.
            /// 
            public IComparer OriginalComparer
            {
                get { return originalComparer; }
            }
    
            /// 
            /// Creates a new reversing comparer.
            /// 
            /// The original comparer to 
            /// use for comparisons.
            public ReverseComparer(IComparer original)
            {
                if (original == null)
                { 
                    throw new ArgumentNullException("original");
                }
                this.originalComparer = original;
            }
    
            /// 
            /// Returns the result of comparing the specified
            /// values using the original
            /// comparer, but reversing the order of comparison.
            /// 
            public int Compare(T x, T y)
            {
                return originalComparer.Compare(y, x);
            }
        }
    }
    

    You'd then use:

    var dict = new SortedDictionary
         (new ReverseComparer(StringComparer.InvariantCulture));
    

    (or whatever type you were using).

    If you only ever want to iterate in one direction, this will be more efficient than reversing the ordering afterwards.

提交回复
热议问题