Hello how can i remove item from generic list here is my code im trying to do it right but i dont know where i make mistake;/
Users us_end = new Users();
foreach (var VARIABLE in ((List<Users>)Application["Users_On"]))
{
if(VARIABLE.Id == (int)Session["Current_Id"])
{
us_end.Name = VARIABLE.Name;
us_end.Id = VARIABLE.Id;
us_end.Data = VARIABLE.Data;
}
}
List<Users> us = ((List<Users>)Application["Users_On"]);
us.Remove(us_end);
Application["Users_On"] = us;
The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.
Removes the first occurrence of the specified element from given list, if the element is present. If the element is not present, the given list is not changed. After removing, it shifts subsequent elements(if any) to left and decreases their indexes by 1.
Java List remove() Methods. There are two remove() methods to remove elements from the List. E remove(int index): This method removes the element at the specified index and return it. The subsequent elements are shifted to the left by one place.
The Remove method removes the first occurrence of a specific object from a List. The Remove method takes an item as its parameter. We can use the RemoveAt method to remove an item at the specified position within a List. The Remove method removes the first occurrence of a specific object from a List.
You have to get the same object to remove, not a copy.
Users us_end;
foreach (var VARIABLE in ((List<Users>)Application["Users_On"]))
{
if(VARIABLE.Id == (int)Session["Current_Id"])
{
us_end = (Users)VARIABLE;
break;
}
}
if (us_end != null)
{
List<Users> us = ((List<Users>)Application["Users_On"]);
us.Remove(us_end);
Application["Users_On"] = us;
}
Edit:
Just to clarify an address here, as pst pointed, you could also implement the IEquatable
interface and some overridings like on the Groo's answer to make it work, but i think it's overkill on this specific subject. Giving this as the most common practice, but making clear that it's also possible to remove items from a list, even if they are diferent instances or even diferent objects with a technique like that.
Ref.: http://msdn.microsoft.com/en-us/library/ms131187.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With