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;
}
}
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With