如何在C#中的数组执行set减法? [英] How to perform set subtraction on arrays in C#?
问题描述
什么是执行在C#中给出两个数组一套减法最简单的方法?显然,这是死很容易在Ruby中。基本上,我只是想从阵列 A
是在阵列 B
删除元素:
What's the simplest way to perform a set subtraction given two arrays in C#? Apparently this is dead easy in Ruby. Basically I just want to remove the elements from array a
that are in array b
:
string[] a = new string[] { "one", "two", "three", "four" };
string[] b = new string[] { "two", "four", "six" };
string[] c = a - b; // not valid
C
应该等于 {一,三化}
。 B - A
将产生 {六个一}
c
should equal { "one", "three" }
. b - a
would yield { "six" }
.
推荐答案
如果你正在使用LINQ,你可以使用的除了运营商的是这样的:
If you're using Linq, you can use the Except operator like this:
string [] c = a.Except(b).ToArray();
编辑: CodeInChaos使得一个好点。如果 A
包含重复,它将删除重复也。另一种方法,以使其功能完全一样的Ruby的版本将是这样的:
CodeInChaos makes a good point. If a
contains duplicates, it will remove any duplicates as well. The alternative to make it function exactly like the Ruby version would be this:
string [] c = a.Where(x=>!b.Contains(x)).ToArray();
这篇关于如何在C#中的数组执行set减法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!