设置A减去设置B.

phc*_*ing 1 .net c# set

我试图以最有效的方式从另一组中拿走一组.因此,如果我有以下集合A和B,那么A_minus_B应该给出{1,2,6}.这是我所拥有的,虽然我相信它不是最有效的方式.

HashSet<int> A = new HashSet<int>{ 1, 2, 3, 4, 5, 6 };
HashSet<int> B = new HashSet<int> { 3, 4, 5 };

HashSet<int> A_minus_B = new HashSet<int>(A);

foreach(int n in A){
    if(B.Contains(n)) A_minus_B.Remove(n);
}
Run Code Online (Sandbox Code Playgroud)

Hos*_*Rad 8

您可以使用该Except()方法.这是代码:

HashSet<int> A_minus_B = new HashSet<int>(A.Except(B)); 
Run Code Online (Sandbox Code Playgroud)