I filled some ObservableCollection<Employe> collection:
// Program.Data.Employees - it is ObservableCollection<Employe>.
Program.Data.Employees.Add(new Employe() { Name="Roman", Patronymic="Petrovich", Surname="Ivanov" });
Program.Data.Employees.Add(new Employe() { Name = "Oleg", Patronymic = "Vladimirovich", Surname = "Trofimov" });
Program.Data.Employees.Add(new Employe() { Name = "Anton", Patronymic = "Igorevich", Surname = "Kuznetcov" });
In other place of my code I try to remove some item from this collection:
// Program.Data.Employees - it is ObservableCollection<Employe>.
Employe x = Program.Data.Employees.First(n => n.Guid == emp.Guid); // x is not null.
Int32 index = Program.Data.Employees.IndexOf(x); // I got -1. Why?
Boolean result = Program.Data.Employees.Remove(x); // I got 'false', and item is not removed. Why?
// But this works fine:
Program.Data.Employees.Clear();
I can clear collection, but I can’t remove necessary item. Why it happens?
UPD: Equals method of my Employe class
public bool Equals(Employe other) {
return
other.Guid == this.Guid &&
String.Equals(other.Name, this.Name, StringComparison.CurrentCultureIgnoreCase) &&
String.Equals(other.Patronymic == this.Patronymic, StringComparison.CurrentCultureIgnoreCase) &&
String.Equals(other.Surname == this.Surname, StringComparison.CurrentCultureIgnoreCase) &&
other.Sex == this.Sex &&
String.Equals(other.Post == this.Post, StringComparison.CurrentCultureIgnoreCase);
}
I tried the following code to reproduce your error:
It worked as expected. I would suggest, you set a breakpont at
var x = ...and check, ifFirst()really returns that itemThen go to the next line and check, if
indexis returned correctly. And finally check again, ifresultis really false.I see several possible causes of your code failing:
x=Program.Data.Employees.First()andProgram.Data.Employees.IndexOf()ObservableCollectiondirectly but some derived class instead which is constructed by your data layer (such asDataServiceCollection, but this one should work fine too). In this case, check the actual type of your collection in the debuggerAnother typical cause of errors with collection would be, if you try to remove items while iterating over the collection (i.e. inside a
foreachloop): but in this case an exception should be thrown (andIndexOfshould work fine), so this would only apply if you use some derived class which implements non-standard behaviour.EDIT (in return to you posting your
Equalmethod)Your
Equalmethod has a serious error in it:should be
Also, if you’re using a Guid, consider only comparing the GUIDs, since this usually means ‘unique identifier’, so it should be enough to identify some entity.