我有一个 HashSet,
var universe = new HashSet<int>();
还有一堆子集,
var sets = new List<HashSet<int>>(numSets);
我想减去一个块,我可以这样做:
var remaining = universe.ExceptWith(sets[0]);
但是ExceptWith
就地工作。我不想修改universe
. 我应该先克隆它,还是有更好的方法?
我想我应该先克隆它?我怎么做?
var universe = new HashSet<int>();
var subset = new HashSet<int>();
...
// clone the universe
var remaining = new HashSet<int>(universe);
remaining.ExceptWith(subset);
不像Except
扩展方法那么简单,但可能更快(您应该运行一些性能测试以确保)
怎么样Except()
?
var x = new HashSet<int>();
var y = new HashSet<int>();
var xminusy = new HashSet<int>(x.Except(y));
Except
我针对克隆和使用 HashSet-native 函数对Linq 的方法进行了基准测试ExceptWith
。这是结果。
static class Program
{
public static HashSet<T> ToSet<T>(this IEnumerable<T> collection)
{
return new HashSet<T>(collection);
}
public static HashSet<T> Subtract<T>(this HashSet<T> set, IEnumerable<T> other)
{
var clone = set.ToSet();
clone.ExceptWith(other);
return clone;
}
static void Main(string[] args)
{
var A = new HashSet<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var B = new HashSet<int> { 2, 4, 6, 8, 10 };
var sw = new Stopwatch();
sw.Restart();
for (int i = 0; i < 1000000; ++i)
{
var C = A.Except(B).ToSet();
}
sw.Stop();
Console.WriteLine("Linq: {0} ms", sw.ElapsedMilliseconds);
sw.Restart();
for (int i = 0; i < 1000000; ++i)
{
var C = A.Subtract(B);
}
sw.Stop();
Console.WriteLine("Native: {0} ms", sw.ElapsedMilliseconds);
Console.ReadLine();
}
}
Linq:1297 毫秒本
机:762 毫秒
散列集必须跟踪其散列算法常数及其溢出箱。集合中的元素通过引用保存。正如 Thomas Levesque 所建议的那样,使用复制构造函数创建一个新的哈希会创建此开销的浅表副本,并且应该非常快。以 James McNellis 建议的方式使用 except() 首先创建一个匿名副本,然后将其传递给复制构造函数,该构造函数使用匿名中的字段来初始化自己的字段。正如托马斯所说,你可能会做一些性能测试,但理论上他的答案应该会超过詹姆斯的答案。顺便说一句,在我看来,浅拷贝不是克隆,因为我相信克隆意味着底层元素也被复制。具有共同元素的哈希集在修改策略时使用副本。
答案很晚,但有时可能有用。
@mpen 使用 Linq 的 except(IEnumerable<>) 回答
这使得 linq 循环通过 IEnumerable 检查它是否包含。
怎么样
setA.Where(i => !setB.Contains(i))
显然,在少数情况下,在循环中“手动”添加项目比复制整个集合然后删除项目更有效。我能想到的一个...
// no more set ops planned? then returning list is an option
public static List<T> ExceptWith<T>(HashSet<T> allObjects, Hashset<T> minus)
{
// Set Capacity of list (allObjects.Count-minus.Count?)
List<T> retlst = new List<T>(allObjects.Count);
foreach( var obj in allObjects) {
if( minus.Contains(obj)==false)
retlst.Add(obj);
}
return retlst;
}
// Special case where quantity of copying will be high
// more expensive in fact than just adding
public static HashSet<T> ExceptWith<T>(HashSet<T> allObjects, HashSet<T> minus)
{
if( minus.Count > allObjects.Count * 7/8 )
{
HashSet<T> retHash = new HashSet<T>();
foreach( var obj in allObjects) {
if( minus.Contains(obj)==false)
retHash.Add(obj);
}
return retHash;
}
else
{
// usual clone and remove
}
}