协调两个对象集合 [英] Reconciling two collections of objects

查看:148
本文介绍了协调两个对象集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,用户可以使用DataGrid修改对象集合。当窗体打开时,我创建一个原始集合的深层副本,如果按下取消按钮,我只是丢弃该副本。



问题是,当确定按钮




  • 修改现有对象的属性


  • 已删除现有物件。

  • 现有物件已重新排序。



由于我需要保留原始引用,因此我无法清除集合并添加修改的项目。



你知道一个简单的算法可以同步两个集合像这样?



我使用C#3.5,所以LINQ是可用的。

解决方案

我刚刚为我正在开发的项目制定了以下算法,我认为它符合您的要求。它遵循以下步骤:


  1. 创建原始列表的浅拷贝。

  2. 清除原始列表。

  3. 修改列表中的Foreach项。


    1. 如果找到原始对象,则会将其添加到列表中并更新其属性。

    2. 到此列表。


此方法维护新订单并重复使用原始参考但要求您的对象具有唯一的标识符。我正在使用一个Guid。

  var originalPersons = m_originalList.ToList 
m_originalList.Clear();
foreach(var modifiedPerson in m_modifiedList)
{
var originalPerson = originalPersons.FirstOrDefault(c => c.ID == modifiedPerson.ID);
if(originalPerson == null)
m_originalList.Add(modifiedPerson);
else
{
m_originalList.Add(originalPerson);
originalPerson.Document = modifiedPerson.Document;
originalPerson.Name = modifiedPerson.Name;
...
}
}

祝你好运。 / p>

I have a form where users can modify a collection of objects using a DataGrid. When the form is opened I create a deep copy of the original collection and if the Cancel button is pressed I just discard that copy.

The problem is that when the OK button is pressed I have to reconcile the changes which might be:

  • Modified properties of existing objects
  • New objects added to any place in the collection.
  • Existing objects removed.
  • Existing objects re-ordered.

Since I need to keep the original references I can't just clear the collection and add the modified items.

Do you know a simple algorithm that would synchronize two collections like this?

I'm using C# 3.5 so LINQ is available.

解决方案

I just worked out the following algorithm for a project I'm working on and I think it complies with your requirements. It follows this steps:

  1. Creates a shallow copy of the original list.
  2. Clears the original list.
  3. Foreach item in the modified list.

    1. If it finds the original object adds it to the list and updates it's properties.
    2. If not just add it to the list.

This method maintains the new order and reuses the original references but requires that your objects have an unique identifier. I'm using a Guid for that.

var originalPersons = m_originalList.ToList();
m_originalList.Clear();
foreach (var modifiedPerson in m_modifiedList)
{
    var originalPerson = originalPersons.FirstOrDefault(c => c.ID == modifiedPerson.ID);
    if (originalPerson == null)
        m_originalList.Add(modifiedPerson);
    else
    {
        m_originalList.Add(originalPerson);
        originalPerson.Document = modifiedPerson.Document;
        originalPerson.Name = modifiedPerson.Name;
        ...
    }
}

Good luck.

这篇关于协调两个对象集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆