从列表集合中删除项目而不删除

本文关键字:删除 删除项目 列表 集合 | 更新日期: 2023-09-27 17:57:12

我正在处理一个集合。我需要从集合中删除一个项目并使用过滤/删除的集合。

这是我的代码

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。
可能是什么问题?

编辑:

原始代码

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

它工作正常。在实际代码中,我正在删除补救项。修复项是 相同的类型,但它属于不同的集合。

从列表集合中删除项目而不删除

您正在将对象传递给您尝试删除但不在您的列表中但在其他列表中复制您的对象Remove,这就是它们没有被删除的原因,使用 List.RemoveAll 方法传递谓词。

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

如果要删除其他一些集合中的许多 id,例如 id 数组

int []ids = new int[3] {1,3,7};
lst.RemoveAll(l => ids.Contains(l.Id))
int removeIndex = list.FindIndex(l => e.Id== 2);
if( removeIndex != -1 )
{
    list.RemoveAt(removeIndex);
}

试试这可能适合你

您粘贴的此原始代码可以完美运行。 它相应地删除了项目。

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

你写错了你的lambda。应该是这样的

var item=empList.Find(l => l.Id== 2);

你需要添加这个打击 menthod Remove():

orginalEmpList.SaveChanges();