“List.Remove” in C# does not remove item?

后端 未结 6 655
面向向阳花
面向向阳花 2020-12-11 03:04

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();
for         


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-11 03:29

    You have to get the same object to remove, not a copy.

    Users us_end;
    
    foreach (var VARIABLE in ((List)Application["Users_On"]))
    {
        if(VARIABLE.Id == (int)Session["Current_Id"])
        {
           us_end = (Users)VARIABLE;
           break;
        }
    }
    
    if (us_end != null)
    {
        List us = ((List)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

提交回复
热议问题