简体   繁体   中英

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;
}

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;
    }
//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;
}

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;
}

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM