【发布时间】:2018-09-27 21:26:16
【问题描述】:
我正在尝试将 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);
}
}
这是我希望发生的事情:
- 我只想在“CustomAttributeID”属性上键入字典
- 我希望字典在枚举键时按“Order”属性排序。
每当我向字典中添加项目时,我都看不到“GetHashCode”或“Equals”方法中的任何断点被击中,但我看到“CompareTo”中的断点被击中。所以不确定 SortedDictionary 在这种情况下如何实际工作。我很想知道如何使 SortedDictionary 在这种情况下工作(我知道我可以通过 Linq 的 OrderBy() 方法做到这一点)。
【问题讨论】:
-
你没有使用 Y.order。
-
是的,顺序不应该是字典键的一部分。它只是用于排序。
-
您没有按订单排序。
-
这是模棱两可的。如果您有两个
CustomAttributeDataKeys 具有相同的CustomAttributeID但具有不同的Order值,您期望会发生什么? -
如果这是您想要的,那么 SortedDictionary 不适合您,因为它不是这样做的。它的工作是维护一个排序的键列表,每个键都映射到一个值,并且它做得很好。在我看来,您想要的是两件事:一个哈希表,它是从 id 到对象的映射,以及一个排序字典,它是从订单到 id 的映射。当您想通过 id 查找时,请查看哈希表。当您想枚举 id 时,请枚举订单并获取 id。您可以轻松构建这样的类型并使其实现 IDictionary。
标签: c# .net sorteddictionary