Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"List.Remove" in C# does not remove item?

Tags:

c#

asp.net

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;
like image 492
vivid Avatar asked Jun 10 '12 18:06

vivid


People also ask

How do I remove items from a list?

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.

How does list Remove work?

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.

Does list have remove method?

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.

How does C# list Remove work?

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.


1 Answers

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

like image 112
Ricardo Souza Avatar answered Sep 19 '22 18:09

Ricardo Souza