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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

int removeIndex = list.FindIndex(l => e.Id== 2);
if( removeIndex != -1 )
{
    list.RemoveAt(removeIndex);
}

Try this may be work for you

Method 3

This original code you have pasted, works perfectly. its removing the items accordingly.

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

Method 4

You wrote your lambda wrong. It should be this way

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

Method 5

You need to add this blow the menthod Remove():

orginalEmpList.SaveChanges();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x