c# - 展平父/子对象链,沿途合并值

标签 c# algorithm parent-child flatten

我们已经盯着这个问题很久了,浪费了宝贵的时间。

我们有这些对象,我们称它们为组件。我们的应用程序允许您基于现有组件 创建一个新组件

父级的所有值都是“继承的”(阅读:可通过 component.Parent 属性访问)除非您覆盖了一个值——例如你想给它一个新名称,但保留其余的父值。

// Exiting parent-child object chain
BaseObject      {Id = 1, Name = "Base", Description = "Base description", Notes = "Awesome object", ParentId = null}
ChildObject1    {Id = 2, Name = "", Description = "", Notes = "", ParentId = 1}
ChildObject2    {Id = 3, Name = "Custom Name", Description = "", Notes = "", ParentId = 2}
ChildObject3    {Id = 4, Name = "", Description = "Final object", Notes = "", ParentId = 3}

现在我想从上到下将其展平,对子项上的任何空值使用父项的现有值。

// End result after flattening/merging
ChildObject3    {Id = 4, Name = "Custom Name", Description = "Final object", Notes = "Awesome object", ParentId = 3}

注意:没有子属性,只有子知道父。 parent 不知道 child 。

如何在不使用丑陋的while(child.Parent != null) 构造和创建previousComponentcurrentComponent 等对象的情况下解决这个问题跟踪设定值。

最佳答案

递归 DeepCopy 方法怎么样,比如:

public class ComponentClass()
{
   public ComponentClass DeepCopy(ComponentClass comp)
   {
       CopyAllNonEmptyPropertiesTo(comp);
       if (comp.StillHasEmptyProperties())
          return Parent.DeepCopy(comp);
       else
          return comp;
   }
}

关于c# - 展平父/子对象链,沿途合并值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26506121/

相关文章:

c# - elmah 自定义提供者和公开事件

c# - 如何杀死一个窗口?

c# - 在整个方法中使用 httpclient 而不会丢失 session 和 cookie

algorithm - 在数组中找到最接近另一种颜色的颜色的最佳算法是什么?

html - Selenium - 在 DIV 下查找子元素

javascript - node.js 中的子/辅助线程

c# - HRESULT : 0x800A03EC on Worksheet. 范围

algorithm - 使用 scala 和 spark 扫描数据的更好方法

algorithm - 是否可以使用一组包含 4 个或更多顶点的对象来实现 A* 路径查找?

css - 如何在保持动态子 div 100% 高度的同时调整父 div 的大小