【问题标题】:c# dictionary<string,string> order by key asc empty value at the endc#dictionary<string,string> 按键排序,最后为空值
【发布时间】:2015-11-02 22:17:45
【问题描述】:

我有一个包含键和值的Dictionary&lt;string,string&gt;

有一个键为空/空。

如何按字母顺序对字典进行排序并在底部/末尾添加空键?

【问题讨论】:

标签: c# dictionary


【解决方案1】:

您可以将SortedDictionary 与自定义Comparer 一起使用。并相应地对其进行排序。

但就像一般建议:如果排序确实对你很重要,那么字典通常不是适合处理这种要求的数据结构。

【讨论】:

    【解决方案2】:

    Dictionary&lt;TKey,TValue&gt; 没有订单。它的后备存储是一个哈希表。如果您想对其施加命令,请使用SortedDictionary&lt;TKey,TValue&gt;:它的后备存储是一棵红黑树(高度平衡二叉树)。

    您应该记住,WRT 对内存使用、插入/删除/查找成本进行了权衡。

    您可能还需要提供合适的比较器来强制执行您需要的排序。

    如果你需要一个比较 null-high 的比较器(大多数内置的都是 null-low),这样的东西就足够了:

    public class MyCustomStringComparer : IComparer<string>
    {
        private readonly StringComparer    baseComparer    ;
        private readonly StringComparison? comparisonStyle ;
        public MyCustomStringComparer( StringComparer baseComparer ) : this( baseComparer , null )
        {
        }
        public MyCustomStringComparer( StringComparison comparisonStyle ) : this( null , comparisonStyle )
        {
        }
        public MyCustomStringComparer() : this( null , null )
        {
        }
        private MyCustomStringComparer( StringComparer comparer , StringComparison? style )
        {
            this.baseComparer = comparer ;
            this.comparisonStyle = style ;
        }
        public int Compare( string x , string y )
        {
            if      ( x == null && y == null ) return  0 ; // two nulls are equal
            else if ( x == null && y != null ) return +1 ; // null is greater than non-null
            else if ( x != null && y == null ) return -1 ; // non-null is less than null
            else // ( x != null && y != null ) ;
            {
                if      ( baseComparer    != null ) return baseComparer.Compare(x,y);
                else if ( comparisonStyle != null ) return string.Compare(x,y,comparisonStyle.Value);
                else                                return x.CompareTo(y);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      相关资源
      最近更新 更多