Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from List Collection not removing

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.

like image 394
Murali Murugesan Avatar asked Feb 02 '13 07:02

Murali Murugesan


1 Answers

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))
like image 104
Adil Avatar answered Oct 07 '22 08:10

Adil