Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any strings exist in 2 string arrays

Tags:

c#

What is the easiest way to check if a string exist in 2 array? p/s Is there is LINQ method to replace this?

// 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;
   }
}
like image 825
Eugene Lim Avatar asked Dec 11 '22 07:12

Eugene Lim


2 Answers

For a case sensitive search, you can just do this

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

As answered Intersect does the the job very well too.

Though if you want a more robust culturally insensitive version

You could use

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

Where culture is the instance of CultureInfo describing the language that the text is written in

like image 106
TheGeneral Avatar answered Dec 24 '22 17:12

TheGeneral


You could intersect the two arrays and then check if there any items in the result:

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

If you care case sensitivity, you can pass a StringComparer as the second argument of Intersect. For example:

var result = stringArray1.Intersect(stringArray2, StringComparer.OrdinalIgnoreCase).Any();
like image 31
DiplomacyNotWar Avatar answered Dec 24 '22 18:12

DiplomacyNotWar