【问题标题】:Looping through a Self Referencing Object循环自引用对象
【发布时间】:2017-08-04 23:06:21
【问题描述】:

我有一个对象,它可以包含自己类型的列表。例如,一个项目类包含各种属性。另一个类,ItemSet 包含一个项目列表,但也可以有一个嵌套的项目集。换句话说,一个 ItemSet 可以包含其他项目集。如下所示:

public class Item
{
    public int Property1 { get; set; }
    public int Property2 { get; set; }
    public int Property3 { get; set; }
    public int Property4 { get; set; }
}

public class ItemSet
{
    public List<Item> Items { get; set; }
    //.
    //.
    //.
    //.
    public List<ItemSet> ItemSets { get; set; }



}

我一直在兜圈子(哈哈,明白了吗?)试图弄清楚如何循环遍历 ItemSet 对象。我一直无法适应父子集的无限可能性。我觉得我做这件事比它需要的要困难得多。

ItemSets = getItemSets(....);
bool hasSets = false;
ItemSet currentItemSet;
foreach(ItemSet itemSet in currentItemSets)
{
     currentItemSet = itemSet;
     hasSets = HasSets(currentItemSet);

     if(hasSets == false)
     {
         //do stuff with currentItemSet
     }

     while(hasSets == true)
     {
         List<ItemSet> SubSets = getItemSets(CurrentItemSet);
         foreach(subset in SubSets)
         {
             currentItemSet = subset;
             //do stuff with currentItemSet

             hasSets = HasSets(currentItemSet);


             ??????????????????????????
         }

     }
}

我知道我在这里很差,但希望得到一些指示。我确实需要能够辨别 Itemset 是否包含子子集并正确处理。

【问题讨论】:

标签: c# loops foreach while-loop


【解决方案1】:

为您的 ItemSet 类定义一个方法,该方法可以遍历集合并在每个集合上递归调用相同的方法。像这样的:

class ItemSet
{
    public List<ItemSet> ItemSets { get; set; }
    public bool hasSets { get; set; }

    public void Loop()
    {
        if (hasSets)
        {
            ItemSets.ForEach(s => s.Loop());
        }

        // do stuff here
    }
} 

更新

或者只是使用递归方法

void Loop(ItemSet set)
{
    set.ItemSets?.ForEach(i => Loop(i));
}

【讨论】:

  • @Connel.O'Donnell 是否可以在不包括对象本身的循环的情况下复制它。我在这里处理遗留代码,我改变的越少越好。 (我更喜欢完全重写,但这不是一个选择)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 2011-12-17
相关资源
最近更新 更多