【问题标题】:Unable to remove the item with .Remove无法使用 .Remove 删除项目
【发布时间】:2011-10-27 09:58:05
【问题描述】:

我正在尝试从数组列表中删除项目,但项目没有被删除,我没有收到任何错误删除不起作用。

protected void ibtnMoveUp_Click(object sender, ImageClickEventArgs e)
    {
        ArrayList ImgArry = new ArrayList();
        ImgArry.Add(SelImgId);
        ImgArry.Add(SelImgpath);//image name
        ImgArry.Add(SelImgName);//image path
        List<int> t1 = new List<int>();
        if (Imgarry1 != null)
            t1 = Imgarry1;//Imaarry1 is the type List<int>
        t1.Add(Convert.ToInt32(ImgArry[0]));
        Imgarry1 = t1;
        List<ArrayList> t = new List<ArrayList>();
        if (newpath.Count > 0)// newpath is the type List<ArrayList> nd creating the viewstate
            t = newpath;
        t.Remove(ImgArry);//Item is not getting remove
        newpath = t;
        for (int i = 0; i < newpath.Count; i++)
        {
            ArrayList alst = newpath[i];
            newtb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i);

        }
        dlstSelectedImages.DataSource = newtb;
        DataBind();
}

【问题讨论】:

标签: c# asp.net arraylist


【解决方案1】:

删除工作正常,但您传递的项目未通过列表中任何项目的相等性测试。

通过提供一个对象来删除将尝试测试该项目与列表中所有项目的相等性(通常通过.Equals()),直到找到一个,然后将其删除。如果没有找到,则不会引发异常。

【讨论】:

  • 你能告诉我如何删除该项目
  • @Rocky 您的示例代码没有说明问题。 newpath 有条件地分配给 t,其中可能有也可能没有任何未知类型的项目。您的问题目前无法直接回答。我只能回答为什么Remove“失败”了。
  • 当我手动检查项目时没有从列表中删除,并且我的相等性通过了
【解决方案2】:

ImgArry 是一个局部变量,引用类型。由于Equals() 的引用类型的默认行为确实是ReferenceEquals(),所以您无法实现它,因为您刚刚创建的实例无论如何都不能放入您的容器中。

您必须先搜索不想删除的项目。例如。 :t.Find(a =&gt; a[0] == SelImgId)

然后你可以t.Remove()之前返回的项目。

【讨论】:

    【解决方案3】:

    Adam Houldsworth 说要写,但我用了一些不同的方法,我的代码如下所示

    我已删除 t.Remove(ImgArry);这一行并添加了

                 List<ArrayList> temp = new List<ArrayList>(t.Count);
                    for (int i = 0; i < t.Count; i++)
                    {
                        ArrayList al = t[i];
                        if (Convert.ToInt32(al[0]) != Convert.ToInt32(ImgArry[0]))
                            temp.Add(al);
                    }
                    t = temp;
    

    【讨论】:

      猜你喜欢
      • 2015-06-10
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多