Reputation: 2965
I have two ObservableCollections, one that contains a current list of employees and one that contains a new one. If the new one contains an employee that is not in the old list, I want to add it to the old list.
If the new list does not contain an employee in the old list, I want to remove it from the old list. (I hope that makes sense).
Here is what I have tried;
foreach (var employee in _currentUsers.ToList())
{
if (!newUsers.Contains(employee))
{
Dispatcher.Invoke(() =>
{
_currentUsers.Remove(employee);
CurrentUsageDataGrid.Items.Refresh();
});
}
}
foreach (var employee in newUsers)
{
if (!_currentUsers.Contains(employee))
{
Dispatcher.Invoke(() =>
{
_currentUsers.Add(employee);
CurrentUsageDataGrid.Items.Refresh();
});
}
}
This is not working as even when I know that the lists haven't changed the Dispatcher.Invoke()
is still firing. Am I misunderstanding how Contains
operates and/or is there a 'better' way of performing a check like this?
Upvotes: 1
Views: 2219
Reputation: 471
As was mentioned above you need to implement/override an Equal method for the comparison. When you do a "Contains" check on 2 class objects, it checks if the 2 objects are equal (not if their properties are). You can do the equal using an id, or you could compute a hashvalue and compare those.
Upvotes: 1
Reputation: 1368
Does your employee class implement IEquatable<T>
interface, the method Contains of ObservableCollection
will use Equal
in that interface to compare object.
Otherwise you may need to use Linq to check for existing employee instead of using Contains
More reference on MSDN, https://msdn.microsoft.com/en-us/library/ms132407(v=vs.100).aspx
Upvotes: 1