List.Remove in C # doesn't delete an item?

Hi, how can I remove an item from the general list here, this is my im code that is trying to do it right, but I don’t know where I am making the 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;
+5
source share
5 answers

You need to delete the same object, 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:

To clarify the address here as pst pointed out, you can also implement the interface IEquatableand some overheads as in Groo's answer to make it work, but I think it overflows with this topic. Giving this as the most common practice, but it is clear that it also allows you to remove items from the list, even if they are different instances or even different objects with a similar technique.

Ref.: http://msdn.microsoft.com/en-us/library/ms131187.aspx

+11

, .NET( Equals , object.Equals). , Remove , .

- , , :

var id = (int)Session["Current_Id"];
var list = (List<Users>)Application["Users_On"];  

// find the exact item to remove.
var itemToRemove = list.FirstOrDefault(u => u.Id = id);

// if found, remove it
if (itemToRemove != null)
{
    list.Remove(itemToRemove);
}
+8

Users - , , Application["Users_On"] ( ), .

, Equals / IEquatable<T> / Users.

List<Users> us = ((List<Users>)Application["Users_On"]);
Users us_end = us.Where(u => u.Id == (int)Session["Current_Id"]).FirstOrDefault();
us.Remove(us_end);
Application["Users_On"] = us;

, - .

+6

:

List<Users> us = ((List<Users>)Application["Users_On"]);
Users us_end = us.First(x => x.ID == (int)Session["Current_Id"]);
us.Remove(us_end);
Application["Users_On"] = us;
0

Remove it in place by finding the element inside the remove statement, and not through an extra copy:

List<Users> us = ((List<Users>)Application["Users_On"]);
us.Remove(us.FirstOrDefault(u => u.ID == (int)Session["Current_Id"]));
Application["Users_On"] = us;
0
source

All Articles