born2fr4g
born2fr4g

Reputation: 1300

How can I compare each element of one string array to every element of another string array?

I've got two string arrays. I want to select one element from the first array and compare to each element of the second array. If element from first array exist in elements of second array i whant to write for example ("Element exist") or something like this.

This should be possible to do with two for loops ?

EDIT

Ok i finaly achived what i wanted usign this code:

string[] ArrayA = { "dog", "cat", "test", "ultra", "czkaka", "laka","kate" };
string[] ArrayB = { "what", "car", "test", "laka","laska","kate" };

bool foundSwith = false;

for (int i = 0; i < ArrayA.Length; i++)
{

   for (int j = 0; j < ArrayB.Length; j++)
   {
       if (ArrayA[i].Equals(ArrayB[j]))
       {
           foundSwith = true;
           Console.WriteLine("arrayA element: " + ArrayA[i] + " was FOUND in arrayB");
       }
   }

   if (foundSwith == false)
   {
      Console.WriteLine("arrayA element: " + ArrayA[i] + " was NOT found in arrayB");
   }
   foundSwith = false;
}

I hope this will help others who will want to compare two arrays ;). its all about this foundSwitch. Thx for help once again.

Upvotes: 1

Views: 11603

Answers (3)

Jose Olivas
Jose Olivas

Reputation: 13

You can also try:

ArrayA.All(ArrayB.Contains);

Upvotes: -1

marvc1
marvc1

Reputation: 3689

foreach (string str in strArray)
{
   foreach (string str2 in strArray2)
   {
       if (str == str2)
       {
          Console.WriteLine("element exists");
       }
   }
}

Updated to display when string does not exist in strArray2

bool matchFound = false;
foreach (string str in strArray)
    {
       foreach (string str2 in strArray2)
       {
           if (str == str2)
           {
              matchFound = true;
              Console.WriteLine("a match has been found");
           }
       }

       if (matchFound == false)
       {
          Console.WriteLine("no match found");
       }
    }

Or another way of doing this in less lines of code:

foreach (string str in strArray)
{
    if(strArray2.Contains(str))
    {
       Console.WriteLine("a match has been found");
    }
    else
    {
       Console.WriteLine("no match found");
    }
}

Upvotes: 1

eyossi
eyossi

Reputation: 4330

foreach (string str in yourFirstArray)
{
   if (yourSearchedArray.Contains(str))
   {
      Console.WriteLine("Exists");
   }
}

Upvotes: 5

Related Questions