Search code examples
c#for-loopnested-loops

Searching two lists with nested loop


I'm trying to find an apartment number which is not already taken. So list<> is a list with already taken apartments and all<> is a list of all the apartments. so I try to iterate through them to find an apartment that is not already taken.

This does not work:

list<> // 4 indexes
all<> // 25 indexes

for (int i = 0;i < all.Count; i++)
{
    for (int j = 0; j < list.Count; j++)
    {   
        if (all[i].apartmentNr != list[j].apartmentNr)
        {
            apartmentNr = all[i].apartmentNr;
        }
    }
}

Solution

  • The problem is that you don't check all the list items so apartmentNr is set on first mismatch, but it's possibly taken on next list item. Thus you need to check all list items, before you can make a conclusion that it's free:

    list<> // 4 indexes
    all<> // 25 indexes
    
    for (int i = 0;i < all.Count; i++)
    {
        bool taken = false;
        for (int j = 0; j < list.Count; j++)
        {   
            if (all[i].apartmentNr == list[j].apartmentNr)
            {
                taken = true;
                break; // no need to check the rest
            }
        }
        if (!taken) {
            apartmentNr = all[i].apartmentNr;
            break; // found first free
        }
    }