I'm trying to delete the list items from the collection using HTTP delete method which takes one parameter of id. For simplicity, I have no guard for checking the provided input and just trying to convert it to int. My expectation is, after invoking delete method with id, let's say 1, the item with index 1 must be deleted from my dishes collection. However, get method still returns all the items. enter image description here
CodePudding user response:
you could make your dishes list static:
private static readonly List<string> dishes = new() { "Oxtail", "Curry Chicken", "Dumplings" };
As long your application is running you can remove items and GetDishes()
will give you the desired result.
As soon as you restart your application you will have the initial 3 items.
If this action should be persistent you need some kind of datastore. E.g. a database
CodePudding user response:
Moving my comment to an answer.
The issue is that controllers are scoped. Meaning that every time a new request comes in, that class gets recreated which means your list of string also gets recreated as it is an instance variable. So when you’re doing you’re next “get” you’re doing it on a brand new instance of the class and therefore a brand new instance of that list.
If you make your list static, it should solve the problem as static variables should last the lifetime of the application.
CodePudding user response:
if you don't want any check the simpliest way is
List<string> dishes = new() { "Oxtail", "Curry Chicken", "Dumplings" };
var id="Dumplings";
dishes.RemoveAll(d => d == id);
or with some check
var itemToRemove = dishes.Where(d => d == id).FirstOrDefault();
if(itemToRemove != null) dishes.Remove(itemToRemove);