我填写了一些ObservableCollection<Employe>
收藏:
// 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" });
在代码的其他位置,我尝试从此集合中删除某些项目:
// 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();
我可以清除收藏,但无法删除必要的项目。为什么会发生这种情况?
更新:Equals
我的方法Employe
类
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);
}
最佳答案
我尝试使用以下代码来重现您的错误:
class Employee
{
public string Name { get; set; }
public Guid Guid { get; set; }
}
// ...
ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
var guid1 = Guid.NewGuid();
employees.Add(new Employee { Name = "Roman", Guid = guid1 });
employees.Add(new Employee { Name = "Oleg", Guid = Guid.NewGuid() });
var x = employees.First(e => e.Guid == guid1);
var index = employees.IndexOf(x); // index = 0, as expected
var result = employees.Remove(x); // result = true, as expected
它按预期工作。我建议您在 var x = ...
处设置断点并检查,如果
- 该集合确实包含您正在查找的项目
- 如果
First()
确实返回该项目
然后转到下一行并检查 index
是否正确返回。最后再次检查结果
是否确实为假。
我发现您的代码失败的几个可能原因:
- 您没有发布完整的代码,并且
x=Program.Data.Employees.First()
和Program.Data.Employees.IndexOf()
之间发生了一些情况 - 您使用多线程代码(这也会导致两个语句之间“发生某些事情”)。这种情况下,需要同步对集合的访问
- 您不直接使用
ObservableCollection
,而是使用一些由数据层构造的派生类(例如DataServiceCollection
,但这个也应该可以正常工作) 。在这种情况下,请在调试器中检查集合的实际类型
集合错误的另一个典型原因是,如果您在迭代集合时尝试删除项目(即在 foreach
循环内):但在这种情况下,应该抛出异常(并且IndexOf
应该可以正常工作),因此这仅适用于您使用某些实现非标准行为的派生类。
编辑(作为您发布Equal
方法的返回)
您的Equal
方法存在严重错误:
String.Equals(other.Patronymic == this.Patronymic, StringComparison.CurrentCultureIgnoreCase)
... // applies also for following comparisons
应该是
String.Equals(other.Patronymic, this.Patronymic, StringComparison.CurrentCultureIgnoreCase)
...
此外,如果您使用 Guid,请考虑仅比较 GUID,因为这通常意味着“唯一标识符”,因此它应该足以识别某个实体。
关于c# - 为什么我无法从 ObservableCollection 中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13429918/