Home > Enterprise >  hi! i'm very new to coding.. is there any other way through which I can write this code to remo
hi! i'm very new to coding.. is there any other way through which I can write this code to remo

Time:01-05

public void RemoveItem(string itemDescription)
{
    MenuItem found = new MenuItem(false, 0, "", ""); // must be a better way - to fix

    foreach (MenuItem item in MenuItems)
    {
        if (item.Description == itemDescription)
        {
            found = item;
        }
    }

    MenuItems.Remove(found);
}

CodePudding user response:

I'm assuming that MenuItems is a List<MenuItem>.

In which case, as Johnathan says in the comments MenuItems.RemoveAll(item => item.Description == itemDescription); will remove all elements in the list that match your criteria and is probably the most efficient option:

public void RemoveItem(string itemDescription)
{
    MenuItems.RemoveAll(item => item.Description == itemDescription);
}

Ideally, though, I'd use an ID field to make sure you're definitely removing the right element.

CodePudding user response:

There are several ways how to improve this code. Some of them were already mentioned.


As commented by @tim-schmelter

// removes the last matching occurrence from the menu and avoids the "dummy" object
public void RemoveItem(string itemDescription)
{
    MenuItem found = null; // this is better

    foreach (MenuItem item in MenuItems)
    {
        if (item.Description == itemDescription)
        {
            found = item;
        }
    }

    if (found != null)
        MenuItems.Remove(found);
}

As originally answered by @SomeBody

// removes the first matching occurrence from the menu
public void RemoveItem(string itemDescription)
{
    foreach (MenuItem item in MenuItems)
    {
        if (item.Description == itemDescription)
        {
            MenuItems.Remove(found);
            break; // or return;
        }
    }
}

// same but replacing the loop with a LINQ approach
public void RemoveItem(string itemDescription)
{
    MenuItem found = MenuItems.FirstOrDefault(item => item.Description == itemDescription);

    if (found != null)
        MenuItems.Remove(found);
}

// removing all occurences (assumes that MenuItems is from type `List<MenuItem>`
public void RemoveItem(string itemDescription)
{
    MenuItems.RemoveAll(item => item.Description == itemDescription);
}
  •  Tags:  
  • Related