带复合键的排序字典:按 1 个属性索引并按另一个属性排序



我正在尝试将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. 我想仅在"自定义属性 ID"属性上键入字典
  2. 我希望字典在枚举键时按"Order"属性排序。

每当我将项目添加到字典中时,我都没有看到命中"GetHashCode"或"Equals"方法中的任何断点,但我看到在"比较"中命中了断点。所以不确定在这种情况下,SortedDictionary实际上如何工作。我很想知道如何使 SortedDictionary 在这种情况下工作(我知道我可以通过 Linq 的 OrderBy(( 方法做到这一点(。

以下是我希望发生的事情:

  1. 我想在"自定义属性 ID"属性上键入字典 只

  2. 我希望字典在我的时候按"订单"属性排序 枚举键。

每当我将项目添加到字典时,我都看不到 命中"GetHashCode"或"Equals"方法中的任何断点,但 我看到在"比较"中命中了一个断点。所以不知道如何 在这种情况下,SortedDictionary实际上可以工作。我会 有兴趣了解如何使排序词典在此工作 场景(我知道我可以通过 Linq 的 OrderBy(( 方法做到这一点(。

根据 MSDN,SortedDictionary使用二叉搜索树存储(根据 MSDN,SortedList使用键值对的排序列表存储(。 这有一些可能与您相关的含义:

  1. SortedDictionary使用IComparer,而不是GetHashCode/EqualsEquals不足以获得总排序,并且类似地使用EqualsCompareTo将是一个坏主意,因此根本不使用Equals
  2. 检索和插入SortedDictionary都是 O(log(n((。
  3. 根据 MSDN,枚举SortedDictionary将保留字典的顺序。 控制SortedDictionary枚举顺序的方法是确保CompareTo以相同的方式对 dctionary 进行排序。

就个人而言,我会犹豫是否通过"Order"属性订购SortedDictionary,因为按此类属性排序意味着您只能按成员的位置查找成员。 这在对象位置和对象平等之间提供了通常不存在的紧密联系。 此时,您不妨改用排序List<T>

最新更新