1

I have an object such that it can contain a list of its own type. For example, an items class contains various properties. Another class, ItemSet consists of a list of items but can also have a nested Item set. In other words, an ItemSet can contain other item sets. This looks as follows:

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; }



}

I've gone in circles(haha get it?) trying to figure out how to loop through the ItemSet object. I have been unable to adjust for the infinite possibilities of parent and child sets. I feel like i a making this much harder than it needs to be.

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);


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

     }
}

I know im significantly off here but was hoping for some pointers. I do need to be able to discern if the Itemset contains children subsets and handle appropriately.

LCaraway
  • 1,257
  • 3
  • 20
  • 48

1 Answers1

6

Define a method for your ItemSet class that can loop through the sets and recursively call the same method on each of them. Something like this:

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
    }
} 

Update

Or just use a recursive method

void Loop(ItemSet set)
{
    set.ItemSets?.ForEach(i => Loop(i));
}
Connell.O'Donnell
  • 3,603
  • 11
  • 27
  • 61
  • @Connel.O'Donnell Would it be possible to duplicate this without including the loop on the object itself. I am dealing with legacy code here and the less i change the better. (I would prefer a full rewrite but that is not an option). – LCaraway Mar 14 '17 at 15:03