比较 ObservableCollections 的任何变化

Comparing ObservableCollections for any changes

我有一个关于 ObservableCollections 比较的问题。基本上,在我的场景中,我有一个业务逻辑方法,它以 ObservableCollection 的形式从数据库中为当前用户获取一组项目。定期地,BackgroundWorker 应该使用上述方法从数据库中获取用户项目,比较它们的变化,如果检测到任何变化,它应该触发 UI 上的更新。问题是,即使没有对数据库中的数据进行任何更改,ObservableCollections 总是不同的。

BackgroundWorker 中使用的方法:

private void UpdateItemList(object sender, DoWorkEventArgs e)
{
    const int updateInterval = 30000;

    while (isItemWorkerRunning)
    {
        Thread.Sleep(updateInterval);
        Application.Current.Dispatcher.Invoke(() => ForceUpdateItemList());
    }
}

private void ForceUpdateItemList()
{
    var userItems = GetItems(userId);

    if (lastUserItems!=userItems)
    {
        //force update
        lastUserItems = userItems;
        //update UI
    }
}

我做错了什么?

我假设 GetItems(userId) 方法返回一个新的 Observable 集合,因为它是一个引用类型,所以它们不相等。新的 userItems 对象与 lastUserItems 对象不同,因此相等性失败。

对于您的情况,最好将 lastUserItems 中的数据与 userItems 中的数据进行比较以检查更改。

您可能想看看这个问题 (Check if two collections are equal),因为它非常相似