循环自引用对象

LCa*_*way 1 c# foreach loops while-loop

我有一个对象,它可以包含自己类型的列表。例如,项目类包含各种属性。另一个类 ItemSet 由一个项目列表组成,但也可以有一个嵌套的 Item 集。换句话说,一个 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; }



}
Run Code Online (Sandbox Code Playgroud)

我一直在兜圈子(哈哈,明白了吗?)试图找出如何循环遍历 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);


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

     }
}
Run Code Online (Sandbox Code Playgroud)

我知道我在这里很远,但希望得到一些指导。我确实需要能够辨别 Itemset 是否包含子集并进行适当处理。

Con*_*ell 6

为您的 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
    }
} 
Run Code Online (Sandbox Code Playgroud)

更新

或者只是使用递归方法

void Loop(ItemSet set)
{
    set.ItemSets?.ForEach(i => Loop(i));
}
Run Code Online (Sandbox Code Playgroud)