减去HashSets(并返回副本)?

mpe*_*pen 17 c# hashset

我有一个HashSet,

var universe = new HashSet<int>();
Run Code Online (Sandbox Code Playgroud)

还有一堆子集,

var sets = new List<HashSet<int>>(numSets);
Run Code Online (Sandbox Code Playgroud)

我想减去一个块,我可以这样做:

var remaining = universe.ExceptWith(sets[0]);
Run Code Online (Sandbox Code Playgroud)

ExceptWith就地工作.我不想修改universe.我应该先克隆它,还是有更好的方法?

Tho*_*que 15

我想我应该先克隆它?我怎么做?

var universe = new HashSet<int>();
var subset = new HashSet<int>();
...

// clone the universe
var remaining = new HashSet<int>(universe);
remaining.ExceptWith(subset);
Run Code Online (Sandbox Code Playgroud)

不像Except扩展方法那么简单,但可能更快(你应该运行一些性能测试来确保)


Jam*_*lis 11

怎么样Except()

var x = new HashSet<int>();
var y = new HashSet<int>();

var xminusy = new HashSet<int>(x.Except(y));
Run Code Online (Sandbox Code Playgroud)

  • @Kirk:终于开始测试了.不对.它仍然慢了约40%.http://programanddesign.com/cs/subtracting-sets/ (3认同)

mpe*_*pen 8

我对Linq的Except方法进行了基准测试,以克隆并使用HashSet本机函数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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Linq:1297 ms
Native:762 ms

http://programanddesign.com/cs/subtracting-sets/