Melanie
Melanie

Reputation: 3111

list Remove method does not remove list item

I have an ASP.Net web app written in C# and it has a List<Employee> object called AffectedEmployees, where Employee is a class I've written. AffectedEmployees is also a property of another class I've written called LitHoldDetails, but I don't think that's pertinent; I just include the information in case I'm wrong, which has, of course, never happened. ;) Anyway, I need to remove a particular Employee object from AffectedEmployees. I first just did a Remove() (Add() works, BTW), but the Employee in question was not removed from AffectedEmployees. So I checked to make sure it was really there by doing a call to Contains(). Contains() doesn't find the Employee in AffectedEmployees, but if I examine the list and compare it to the Employee in the debugger, the Employee is indeed in Affected Employees. I've compared the two with a fine tooth comb and I see no difference in the data. What am I doing wrong? Here's my code:

Employee emp = new Employee().FindByLogin(item.Key.ToString());
if (CurrentLitHoldDetails.AffectedEmployees.Contains(emp))
    CurrentLitHoldDetails.AffectedEmployees.Remove(emp);

Note: FindByLogin() initiates emp and fills it with data. item.Key.ToString() is coming from a Hashtable that contains all the Employees I need to remove

Upvotes: 1

Views: 188

Answers (2)

Grant Winney
Grant Winney

Reputation: 66439

You're creating a new Employee object that couldn't possibly exist in the list yet, then trying to remove it. So it doesn't find that exact object (even if the contents of the new Employee object match some other Employee object in the list) and doesn't remove it. If you place a breakpoint on the line with Remove on it, you'll see it doesn't get hit.

Try using RemoveAll to remove all elements matching some condition. (I'm doing a bit of guessing here since I don't know what your classes look like exactly.)

CurrentLitHoldDetails.AffectedEmployees.RemoveAll(x => x.Login == item.Key.ToString());

Upvotes: 4

Ann L.
Ann L.

Reputation: 13965

Remove and Contains test for the presence of the exact object you're trying to remove, not just one with identical data. So when you create a new Employee object, it's looking for that exact object. It doesn't find it, because that exact object has never been added to AffectedEmployees.

This is called "reference equality" and is the default behavior. If you want Remove and Contains to determine equality based on property values, you will need to override the Equals and GetHashCode methods on your Employee object. (See here for Microsoft's documentation on Object.GetHashCode().)

Upvotes: 3

Related Questions