Home > Mobile >  How to iterate each element of 2 arrays?
How to iterate each element of 2 arrays?

Time:05-19

I have 2 arrays communes and arrListStr.

I'm using if else to compare array element communes vs array arrListStr, but I want communes array to have to go through all elements in array arrListStr if there is no duplicate to last position then exception.

I'm confused and don't know what to do? Thanks if someone help me !

Here is the code :

                /// communes list
               /// arrListStr list
               for (int a = 0; a < communes.Count; a  )
                {
                    for (int b = 0; b < arrListStr.Length; b  )
                    {
                        if (communes[a].Name == arrListStr[b])
                        {
                            count  ;
                            rtbResult.AppendText("\n"   " Successfully - "   count);
                        }
                        else
                        {
                            count  ;
                            rtbResult.AppendText("\n"   " Fail - "   count);
                        }
                    } 
                 }

CodePudding user response:

A simple solution would be to add a boolean to track if the item is found or not:

for (int a = 0; a < communes.Count; a  )
{

    bool isFound = false; // track if this item was found

    for (int b = 0; b < arrListStr.Length; b  )
    {
        if (communes[a].Name == arrListStr[b])
        {

            isFound = true; // mark as found

            count  ;
            rtbResult.AppendText("\n"   " Successfully - "   count);
        }
        else
        {
            count  ;
            rtbResult.AppendText("\n"   " Fail - "   count);
        }
    }


    // do something when not found
    if (!isFound)
    {
        throw new Exception("not found");
    }
 }

CodePudding user response:

Given two arrays, you can iterate over the elements in an array using foreach.

foreach (var c in communes)
{
    foreach (var s in arrListStr)
    {
        count  ;
        if (c == s)
        {
            rtbResult.AppendText("\n"   " Successfully - "   count);
        }
        else
        {
            rtbResult.AppendText("\n"   " Fail - "   count);
        }
    }
}
  • Related