【发布时间】:2020-06-28 00:43:02
【问题描述】:
HashSet<ReadOnlyCollection<int>> test1 = new HashSet<ReadOnlyCollection<int>> ();
for (int i = 0; i < 10; i++) {
List<int> temp = new List<int> ();
for (int j = 1; j < 2; j++) {
temp.Add (i);
temp.Add (j);
}
test1.Add (temp.AsReadOnly ());
}
这里test1是{[0,1], [1,1], [2,1], [3,1], [4,1], [5,1], [6,1], [ 7,1], [8,1], [9,1]}
HashSet<ReadOnlyCollection<int>> test2 = new HashSet<ReadOnlyCollection<int>> ();
for (int i = 5; i < 10; i++) {
List<int> temp = new List<int> ();
for (int j = 1; j < 2; j++) {
temp.Add (i);
temp.Add (j);
}
test2.Add (temp.AsReadOnly ());
}
这里的test2是{[5,1], [6,1], [7,1], [8,1], [9,1]}
test1.ExceptWith(test2);
这样做之后,我希望 test1 是 {[0,1], [1,1], [2,1], [3,1], [4,1]},但它给了我原来的测试1.
如何解决这个问题?或者有没有其他方法可以做同样的事情?谢谢!
【问题讨论】:
-
简短回答:您可以为您的收藏定义一个自定义的 EqualityComparer。目前,它们通过实例(作为对象)进行比较,每个新的 HashSet 或 List 都是不同的,即使它们包含相同的元素。
-
你明白它为什么会这样吗?
-
@Pac0 你的意思是我应该定义一个类来包含这些值并覆盖它的 Equals 和 GetHashCode 方法吗?谢谢!
-
@mjwills 我的猜测是,当 C# 对 相同的 ReadOnlyCollection
进行哈希处理时,例如 [1,2],它会返回 不同的哈希值对于价值相同的收藏,但我不知道如何解决这个问题,谢谢您的回复! -
如果这是您真正想要使用的数据,请将其改为 Tuple
。
标签: c# hashset readonly-collection