Check if any strings exist in 2 string arrays

What is the easiest way to check if a row exists in a 2 array? p / s Is there a LINQ way to replace?

// Old school method
bool result = false;
var stringArray1 = new string[] { "ABC", "EFG", "HIJ" };
var stringArray2 = new string[] {"123", "456", "ABC"};
for (var i = 0; i < stringArray1.Count; i++) {
    var value1 = stringArray1[i];
   for (var j = 0; j < stringArray2.Count; j++) {
       var value2 = stringArray2[j];
       if(value1 == value2)
           result = true;
   }
}
+4
source share
2 answers

For case sensitive search you can just do it

var result = stringArray1.Any(x => stringArray2.Contains(x));

As answered, it Intersectalso works very well.

If you need a more robust version with cultural insensitivity

you can use

var culture = new CultureInfo("en-US");
var result =  stringArray1.Any(x => 
                  stringArray2.Any(y => 
                      culture.CompareInfo.IndexOf(x, y, CompareOptions.IgnoreCase) >= 0));

Where cultureis an instance CultureInfodescribing the language in which the text is written in

+7
source

You can cross two arrays and then check to see if there are elements in it:

var stringArray1 = new string[] { "ABC", "EFG", "HIJ" };
var stringArray2 = new string[] { "123", "456", "ABC" };
var result = stringArray1.Intersect(stringArray2).Any();

, StringComparer Intersect. :

var result = stringArray1.Intersect(stringArray2, StringComparer.OrdinalIgnoreCase).Any();
+6

Source: https://habr.com/ru/post/1695733/


All Articles