比较两个数组并从第二个数组中删除相同(相交)的值

Compare Two Arrays And Delete Same (Intersect) Value From Second Array

       string[] one={"my", "5", "two", "array", "hey?", "good", "day"};
       string[] two={"hello!", "how", "good", "day", "us", "very", "two", "hard", "learn", "it"};

例如:我有上面这些数组,我想比较它们,比较后从两个字符串[]中删除相同的值。所以,当我编译代码时,我的数组将是这样的;

       string[] one={"my", "5", "two", "array", "hey?", "good", "day"};
       string[] two={"hello!", "how", "us", "very", "hard", "learn", "it"};

注意:抱歉,我无法对此产生任何想法。

只需在 Linq 语句中使用 WhereContains,然后 ToArray

简单来说,

  1. 它通过检查数组 one 是否不包含两个

  2. 的每个元素来过滤数组 two
  3. 将输出转换回数组

  4. 将它赋值给你的变量 two

例子

string[] one={"my", "5", "two", "array", "hey?", "good", "day"};
string[] two = { "hello!", "how", "good", "day", "us", "very", "two", "hard", "learn", "it" };

two = two.Where(x => !one.Contains(x)).ToArray();

Console.WriteLine(string.Join(",", two));

注意,这里区分大小写

输出

hello!,how,us,very,hard,learn,it

或者更高效的方法是使用 Except,我完全忘记了(感谢评论)

two = two.Except(one).ToArray();

Enumerable.Except Method

Produces the set difference of two sequences.

Enumerable.Where Method

Filters a sequence of values based on a predicate.

Enumerable.Contains Method

Determines whether a sequence contains a specified element.

Enumerable.ToArray(IEnumerable) Method

Creates an array from a IEnumerable.