带复合键的SortedDictionary:按1个属性建立索引,然后按另一个属性进行排序

时间:2018-09-25 22:02:46

标签: c# .net sorteddictionary

我正在尝试将SortedDictionary实现为:

public IDictionary<CustomAttributeDataKey, object> Data { get; } = new SortedDictionary<CustomAttributeDataKey, object>();

我已将CustomAttributeDataKey定义为:

public class CustomAttributeDataKey : IComparable {
    public long CustomAttributeID { get; set; }
    public int Order { get; set; }

    //ASSUMING this is used to check if there is a collision of keys
    protected bool Equals(CustomAttributeDataKey other) {
        return CustomAttributeID == other.CustomAttributeID;
    }

    //ASSUMING this is used to check if there is a collision of keys
    public override bool Equals(object obj) {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((CustomAttributeDataKey) obj);
    }

    //ASSUMING this is used to check if the key exists in the dictionary
    public override int GetHashCode() {
        return CustomAttributeID.GetHashCode();
    }

    //ASSUMING this is used for sorting
    public int CompareTo(object y) {
        if (y == null)
            return 0;

        return this.Order.CompareTo(((CustomAttributeDataKey) y).Order);
    }
}

这就是我想发生的事情:

  1. 我只想将字典键入“ CustomAttributeID”属性上
  2. 我希望字典在枚举键时按“ Order”属性排序。

每当我向字典中添加项目时,在“ GetHashCode”或“ Equals”方法中都看不到任何断点,但是在“ CompareTo”中却遇到了断点。因此,不确定在这种情况下SortedDictionary实际如何工作。我很想知道在这种情况下如何使SortedDictionary工作(我知道我可以通过Linq的OrderBy()方法来做到这一点。)

1 个答案:

答案 0 :(得分:0)

  

这就是我想发生的事情:

     
      
  1. 我想在“ CustomAttributeID”属性上键入字典   仅

  2.   
  3. 我希望字典在我排序时按“ Order”属性排序   枚举键。

  4.   
     

每当我向字典中添加项目时,我都看不到   遇到“ GetHashCode”或“ Equals”方法中的任何断点,但   我看到“ CompareTo”中有一个断点。所以不确定   在这种情况下,SortedDictionary实际上可以工作。我会   有兴趣了解如何使SortedDictionary在此工作   场景(我知道我可以通过Linq的OrderBy()方法来做到这一点)。

The MSDNSortedDictionary使用二进制搜索树存储(每The MSDNSortedList使用键值对的排序列表存储)。这可能与您有一些联系:

  1. SortedDictionary使用IComparer,而不使用GetHashCode / EqualsEquals不足以获得全部订购,并且同时使用EqualsCompareTo并不是一个好主意,因此根本不使用Equals
  2. 检索和插入SortedDictionary均为O(log(n))。
  3. The MSDN枚举SortedDictionary保留字典的顺序。控制SortedDictionary的枚举顺序的方法是确保CompareTo以相同的方式对字典进行排序。

就我个人而言,我会犹豫是否要通过“ Order”属性对SortedDictionary进行排序,因为按这种属性进行排序意味着您只能按其位置查找成员。这在对象位置和对象相等性之间提供了牢固的联系,而这通常是不存在的。此时,您也可以改用排序后的List<T>