如何使用ExceptWith类型的HashSet >在C#中?

问题描述 投票:0回答:1
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]},但它给了我原始的test1 。如何解决这个问题?还是有其他方法可以做同样的事情?谢谢!

c# hashset readonly-collection
1个回答
0
投票

这里您具有ExceptWith的实现:

https://github.com/microsoft/referencesource/blob/3b1eaf5203992df69de44c783a3eda37d3d4cd10/System.Core/System/Collections/Generic/HashSet.cs#L532

其实际作用是:

 // remove every element in other from this
 foreach (T element in other) {
    Remove(element);
 }

并删除:

https://github.com/microsoft/referencesource/blob/3b1eaf5203992df69de44c783a3eda37d3d4cd10/System.Core/System/Collections/Generic/HashSet.cs#L287

 if (m_slots[i].hashCode == hashCode && m_comparer.Equals(m_slots[i].value, item)) {

因此,如果哈希码不同,则跳过它一个小测试:

    List<int> temp = new List<int> ();
     temp.Add(1);
     temp.Add(2);

    HashSet<ReadOnlyCollection<int>> test1 = new HashSet<ReadOnlyCollection<int>> ();
    HashSet<ReadOnlyCollection<int>> test2 = new HashSet<ReadOnlyCollection<int>> ();
    test1.Add (temp.AsReadOnly ());
    test2.Add (temp.AsReadOnly ());

    Console.WriteLine(test1.First().GetHashCode() == test2.First().GetHashCode());
© www.soinside.com 2019 - 2024. All rights reserved.