[英]C# WPF compare List<T> to Datagrid.ItemsSource
我将我的private List<MaintenanceWindow> tempMaintenanceWindows
到Datagrid,并使用户能够编辑Datagrid中的项目以及添加新项目。 这很好用。
现在我想到了如果在没有先按下保存按钮的情况下关闭窗口,如何回滚用户所做的更改。 基本上,我想将Datagrid.ItemsSource与我填充的临时List进行比较,如下所示:
foreach (MaintenanceWindow mainWin in maintenanceWindowList)
tempMaintenanceWindows.Add(new MaintenanceWindow {from = mainWin.from, to = mainWin.to, abbreviation = mainWin.abbreviation, description = mainWin.description, hosts = mainWin.hosts });
我比较这两个:
if (!tempMaintenanceWindows.SequenceEqual((List<MaintenanceWindow>)mainWinList.ItemsSource))
但是SequenceEqual的结果似乎总是错误的,尽管在调试代码时,它们看起来完全相同。
希望有人能提供帮助。 谢谢。
Quentin Roger提供了一种方法解决方案,但是我希望发布我的代码,这可能不是最好的方法,但它适合我的应用案例。
所以这就是我覆盖MaintenanceWindow对象的Equals方法的方法:
public override bool Equals (object obj)
{
MaintenanceWindow item = obj as MaintenanceWindow;
if (!item.from.Equals(this.from))
return false;
if (!item.to.Equals(this.to))
return false;
if (!item.description.Equals(this.description))
return false;
if (!item.abbreviation.Equals(this.abbreviation))
return false;
if (item.hosts != null)
{
if (!item.hosts.Equals(this.hosts))
return false;
}
else
{
if (this.hosts != null)
return false;
}
return true;
}
默认情况下,SequenceEqual将比较调用相等函数的每个项,是否重写相等? 否则,它会比较一个类的内存地址。
另外,我建议您在查找不可变列表比较时使用FSharpList 。
“所以在覆盖方法中我是否必须比较MaintenanceWindow类的每个字段”
你必须比较每个有意义的字段,是的。
如果您将MaintenanceWindow声明为:
正如我在评论中所说,你必须比较每个重要的字段。在下面的实现中我选择了描述,所以如果两个MaintenanceWindow
得到相同的description
它们将被视为等于,并且SequenceEquals将按预期工作。
internal class MaintenanceWindow
{
public object @from { get; set; }
public object to { get; set; }
public object abbreviation { get; set; }
private readonly string _description;
public string Description => _description;
public MaintenanceWindow(string description)
{
_description = description;
}
public string hosts { get; set; }
public override bool Equals(object obj)
{
return this.Equals((MaintenanceWindow)obj);
}
protected bool Equals(MaintenanceWindow other)
{
return string.Equals(_description, other._description);
}
public override int GetHashCode()
{
return _description?.GetHashCode() ?? 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.