簡體   English   中英

C#WPF比較列表 <T> 到Datagrid.ItemsSource

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM