从列表集合中删除项目但不删除 [英] Remove item from List Collection not removing

查看:55
本文介绍了从列表集合中删除项目但不删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个收藏.我需要从集合中删除一个项目,然后使用过滤/删除的集合.

I am working on a collection. I need to remove one item from a collection and use the filtered/removed collection.

这是我的代码

public class Emp{
  public int Id{get;set;}
  public string Name{get;set;}
}

List<Emp> empList=new List<Emp>();
Emp emp1=new Emp{Id=1, Name="Murali";}
Emp emp2=new Emp{Id=2, Name="Jon";}
empList.Add(emp1);
empList.Add(emp2);

//Now i want to remove emp2 from collection and bind it to grid.
var item=empList.Find(l => l.Id== 2);
empList.Remove(item);

即使在删除我的收藏夹仍显示计数为2的项目后,问题仍然存在.
可能是什么问题?

The issue is even after removing the item my collection still shows count 2.
What could be the issue?

原始代码

  var Subset = otherEmpList.FindAll(r => r.Name=="Murali");

   if (Subset != null && Subset.Count > 0)
   {
    foreach (Empl remidateItem in Subset )
    {
       Emp removeItem = orginalEmpList.Find(l => l.Id== 
                                          remidateItem.Id);
                    if (removeItem != null)
                    {
                        orginalEmpList.Remove(remidateItem); // issue here

                    }
      }
    }

工作正常.在实际代码中,我正在删除remediateItem.原"remediateItem"为 相同的类型,但属于不同的集合.

It is working fine. In actual code i was removing remediateItem. remediateItem was same type but it belongs to different collection.

推荐答案

您正在将对象传递给Remove,这些对象不在您要尝试删除的列表中,而是对象的副本其他列表,这就是为什么不删除它们的原因,请使用

You are passing the objects to Remove which are not in your list you are trying to remove but copy of your object in other the list, that is why they are not being deleted, Use List.RemoveAll method to pass the predicate.

lst.RemoveAll(l => l.Id== 2);

如果您要删除其他一些集合(例如ID数组)中的许多ID

If you want to remove many ids in some other collections like array of ids

int []ids = new int[3] {1,3,7};
lst.RemoveAll(l => ids.Contains(l.Id))

这篇关于从列表集合中删除项目但不删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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