I am working on a collection. I need to remove one item from a collection and use the filtered/removed collection.
Here is my code
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);
The issue is even after removing the item my collection still shows count 2.
What could be the issue?
EDIT:
Original Code
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
}
}
}
It is working fine. In actual code i was removing remediateItem. remediateItem was same type but it belongs to different collection.
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);
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With