We help IT Professionals succeed at work.

# Comparing arrays of strings

on
If I have two arrays of words, how can I easily find the number of matches?

List 1           List 2
Cat              Dog
Dog             Cow
Cow            Lion
Puppy         Zebra
Lion            Elephant

The sequence is a different test I can do. In this example, there are three matches.

How can I easily code this?

Thanks,
newbieweb
Comment
Watch Question

## View Solutions Only

Most Valuable Expert 2011
Top Expert 2015

Commented:
Can you use Linq?
Senior Software Engineer
Top Expert 2009
Commented:
If l1 and l2 contains your words,
then the attached code will compare l1 against l2

``````public int GetNumberMatches(List<string> l1, List<string> l2)
{
int matches = 0;
if (l1.Count == 0 || l2.Count == 0)
return matches;
foreach (var item in l2)
{
if (l1.Contains(item))
matches++;
}
return matches;
}
``````

Commented:
I can imagine an easy regex solution as well, but I dont really see the point. This is probably more effective.

Linq would also be a good choice.
``````List<string> list1 = new List<string>() { "Cat", "Dog", "Cow", "Puppy", "Lion" };
List<string> list2 = new List<string>() { "Dog", "Cow", "Lion", "Zebra", "Elephant" };

Int32 matches = 0;

foreach (string s1 in list1)
{
if (list2.Contains(s1)) matches += 1;
}
``````
Commented:
Dim aList() As String
Dim bList() As String
Dim Matches As Integer = 0
For Each A As String In aList
For Each B As String In bList
If (A.ToUpper() = B.ToUpper()) Then  'ignore case
Matches = Matches + 1
End If
Next
Next

Commented:
string[] aList;
string[] bList;
int Matches = 0;
foreach (string A in aList) {
foreach (string B in bList) {
if ((A.ToUpper() == B.ToUpper())) {
// ignore case
Matches = (Matches + 1);
}
}
}
Software Engineer

Commented:
Yes, I can use Linq. The other code seems good but brute force.  What can you suggest wth Linq?
Most Valuable Expert 2011
Top Expert 2015
Commented:
Here's a possible Linq version:

``````string[] List1 = { "Cat", "Dog", "Cow", "Puppy", "Lion" };
string[] List2 = { "Dog", "Cow", "Lion", "Zebra", "Elephant" };

var matchCount = (from l1 in List1
join l2 in List2
on l1 equals l2
select l1).Count();
``````
Most Valuable Expert 2011
Top Expert 2015

Commented:
If the lists can respectively contain duplicates, then you can call Distinct within the query:

``````var matchCount = (from l1 in List1.Distinct()
join l2 in List2.Distinct()
on l1 equals l2
select l1).Count();
``````
Software Engineer

Commented:
Nice code. Thanks,