两个字符串数组交集(忽略大小写)数组、大小写、字符串、两个

2023-09-04 00:14:03 作者:村霸

我有两个数组:

 的String [] ARRAY1 = {红,蓝,绿,黑};
字符串[] ARRAY2 = {蓝,黄,黑};
 

我只需要匹配的字符串在一个阵列中(不区分大小写)。

结果应该是:

 的String []的结果= {蓝,黑}或{蓝,黑};
 

解决方案

怎么样的 Enumerable.Intersect 和StringComparer组合:

  //其他选项包括StringComparer.CurrentCultureIgnoreCase
//或StringComparer.InvariantCultureIgnoreCase
VAR的结果= array1.Intersect(ARRAY2,StringComparer.OrdinalIgnoreCase);
 
力扣刷题六 两个数组的交集

I have two arrays:

string[] array1 = { "Red", "blue", "green", "black" };
string[] array2 = { "BlUe", "yellow", "black" };

I need only the matching strings in one array (ignoring case).

Result should be:

string[] result = { "blue", "black" } or { "BlUe", "black" };

解决方案

How about an Enumerable.Intersect and StringComparer combo:

// other options include StringComparer.CurrentCultureIgnoreCase
// or StringComparer.InvariantCultureIgnoreCase
var results = array1.Intersect(array2, StringComparer.OrdinalIgnoreCase);