“列表.删除";在C#中不会删除项目? [英] "List.Remove" in C# does not remove item?

查看:80
本文介绍了“列表.删除";在C#中不会删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我如何从通用列表中删除项目,这是我的代码,我想正确地执行此操作,但是我不知道我在哪里犯错;/

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;

推荐答案

您必须获取要删除的同一对象,而不是副本.

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;
}

仅在此处澄清一个地址,您也可以实现IEquatable接口和一些类似Groo答案的替代方法以使其起作用,但是我认为这在这个特定主题上是过大的.将此作为最常见的做法,但要明确说明,即使使用类似的技术,即使它们是不同的实例甚至是不同的对象,也可以从列表中删除它们.

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.

引用: http://msdn.microsoft.com/zh-CN/library/ms131187.aspx

这篇关于“列表.删除";在C#中不会删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆