MBrewers
MBrewers

Reputation: 141

C# List loop within a loop?

I'm working on a class project and here is what I have so far. I know the code returns true when it finds a match but I want it to keep looping until no more instances are found.

I've looked at numerous sites on for/while loops but I can't seem to get the syntax correct and/or it doesn't work when applying the logic.

public bool Remove(T toRemove)
{
    for (int i = 0; i < count; i++)
    {
        if (items[i].Equals(toRemove))
        {
            int removeIndex = i;
            for (int j = removeIndex; j < count - 1; j++)
            {
                items[j] = items[j + 1];
            }
            return true;
        }
    }
    return false;
}

Upvotes: 1

Views: 120

Answers (4)

Mureinik
Mureinik

Reputation: 311198

Just save the result in a variable and return it after the loop is complete:

public bool Remove(T toRemove)
{
    bool result = false;
    for (int i = 0; i < count; i++)
    {
        if (items[i].Equals(toRemove))
        {
            int removeIndex = i;
            for (int j = removeIndex; j < count - 1; j++)
            {
                items[j] = items[j + 1];
            }
            result = true;
        }
    }
    return result;
}

Upvotes: 1

Kevin
Kevin

Reputation: 7309

I think what you want to do is declare a bool called "result" and instantiate it to false. In the loop where you are returning true, set "result" to true. At the end, where you are returning false, return "result"

Upvotes: 0

Ryan Wilson
Ryan Wilson

Reputation: 10765

//Use a boolean variable and set it to true if an item is found, 
//and continue your loop until you go through all elements, then return the boolean value.  

public bool Remove(T toRemove)
{
        bool match= false; //boolean to track if any match is found
        for (int i = 0; i < count; i++)
        {
            if (items[i].Equals(toRemove))
            {
                int removeIndex = i;
                for (int j = removeIndex; j < count - 1; j++)
                {
                    items[j] = items[j + 1];
                }
                match= true;
            }
        }

        return match;
}

Upvotes: 1

apomene
apomene

Reputation: 14389

If you want to complete the loop, do not return. Instead hold the result on a var you should return at the end:

    public bool Remove(T toRemove)
    {
        bool result = false;
        for (int i = 0; i < count; i++)
        {
            if (items[i].Equals(toRemove))
            {
                int removeIndex = i;
                for (int j = removeIndex; j < count - 1; j++)
                {
                    items[j] = items[j + 1];
                }
                result = true;
            }
        }
        return result;
    }

Upvotes: 2

Related Questions