Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 集合A减去集合B_C#_.net_Set - Fatal编程技术网

C# 集合A减去集合B

C# 集合A减去集合B,c#,.net,set,C#,.net,Set,我正试图以最有效的方式将一套从另一套中拿走。如果我有下面的集合A和B,那么A_减去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<

我正试图以最有效的方式将一套从另一套中拿走。如果我有下面的集合A和B,那么A_减去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);
}
HashSet A=新的HashSet{1,2,3,4,5,6};
HashSet B=新的HashSet{3,4,5};
HashSet A_减B=新的HashSet(A);
foreach(A中的int n){
如果(B.Contains(n))A_减去B.Remove(n);
}

您可以使用
Except()
方法。代码如下:

HashSet<int> A_minus_B = new HashSet<int>(A.Except(B)); 
HashSet A_减B=新的HashSet(A.Except(B));
您可以使用,它将通过删除
B
中的项目来修改
A

A.ExceptWith(B);
您也可以使用
,但
将返回新集合

使用以下命令:

var setA= new HashSet<int>();
var setB= new HashSet<int>();
...

var remaining = new HashSet<int>(setA);
remaining.ExceptWith(setB);
var setA=newhashset();
var setB=新的HashSet();
...
var剩余=新哈希集(setA);
剩余。除(挫折)外;

remaining
是您的新筛选集。

请查看LINQ中的
扩展方法,但
除外。您可以从一个列表中选择另一个列表中不存在的所有项目。请注意,这是在修改集合
A
,而不是返回表示集合差异的新集合。谢谢,我修改了答案以公开它。