从一个哈希集中删除不在另一个哈希集中的元素?
Remove elements from one Hashset where NOT in another Hashset?
我知道 hashsetA.Except(hashsetB)
从 hashsetA
中删除存在于 hashsetB
中的元素。但是,我想从 hashsetA
中删除 不 存在于 hashsetB
中的元素。
目前我只是将 hashsetA
复制到一个新的 Hashset
然后使用 ExceptWith()
两次:
hashsetC = new HashSet<var>(hashsetA);
hashsetC.ExceptWith(hashsetB);
hashsetA.ExceptWith(hashsetC);
它的性能足以满足我的目的,但我想知道是否有内置方法可以使 faster/more 简洁?
还是我错过了从集合中 select 的明显方法?
res = hashsetA.Where(p=> hashsetB.Contains(p)).
鉴于哈希集中的查找是 O(1),总和应为 O(n)。
只需使用IntersectWith
method。
hashsetA.IntersectWith(hashsetB);
我知道 hashsetA.Except(hashsetB)
从 hashsetA
中删除存在于 hashsetB
中的元素。但是,我想从 hashsetA
中删除 不 存在于 hashsetB
中的元素。
目前我只是将 hashsetA
复制到一个新的 Hashset
然后使用 ExceptWith()
两次:
hashsetC = new HashSet<var>(hashsetA);
hashsetC.ExceptWith(hashsetB);
hashsetA.ExceptWith(hashsetC);
它的性能足以满足我的目的,但我想知道是否有内置方法可以使 faster/more 简洁? 还是我错过了从集合中 select 的明显方法?
res = hashsetA.Where(p=> hashsetB.Contains(p)).
鉴于哈希集中的查找是 O(1),总和应为 O(n)。
只需使用IntersectWith
method。
hashsetA.IntersectWith(hashsetB);