调和对象的两个集合

编程入门 行业动态 更新时间:2024-10-25 00:36:27
本文介绍了调和对象的两个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

的问题是,当确定按钮按我不得不调和的变化可能是:

  • 现有对象的修改的属性
  • 新的对象添加到集合中的任何地方。
  • 现有对象中删除。
  • 现有对象重新排序。

因为我需要保留原来的引用我不能只清除收集并添加修改的项目。

你知道一个简单的算法,将同步两个集合这样?

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

解决方案

我刚刚制定了以下算法的一个项目我的工作,我认为它与你的要求。它遵循这样的步骤:

  • 创建原始列表的浅表副本
  • 清除原名单。
  • 在Foreach源修改列表项。
  • 如果它发现原始对象将其添加到列表中,并更新它的属性。
  • 如果不仅它添加到列表中。
  • 这方法保持新秩序并重新使用原来的引用,但要求你的对象具有一个唯一的标识符。我使用一个GUID为

    VAR originalPersons = m_originalList.ToList(); m_originalList.Clear(); 的foreach(在m_modifiedList VAR modifiedPerson) { VAR originalPerson = originalPersons.FirstOrDefault(C => c.ID == modifiedPerson.ID); 如果(originalPerson == NULL) m_originalList.Add(modifiedPerson); ,否则 { m_originalList.Add(originalPerson); originalPerson.Document = modifiedPerson.Document; originalPerson.Name = modifiedPerson.Name; :} }

    祝你好运。

    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:

  • Creates a shallow copy of the original list.
  • Clears the original list.
  • Foreach item in the modified list.

  • If it finds the original object adds it to the list and updates it's properties.
  • 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.

    更多推荐

    调和对象的两个集合

    本文发布于:2023-11-29 00:18:43,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1644536.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:对象   两个

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!