簡體   English   中英

從列表集中刪除項目而不刪除

[英]Remove item from List Collection not removing

我正在研究一個系列。 我需要從集合中刪除一個項目並使用過濾/刪除的集合。

這是我的代碼

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

                    }
      }
    }

它工作正常。 在實際代碼中我刪除了remediateItem。 remediateItem是同一類型,但它屬於不同的集合。

您正在將對象傳遞給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);
}

試試這可能對你有用

你寫的lambda錯了。 應該是這樣的

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

您粘貼的原始代碼完美無缺。 它相應地刪除項目。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM