I am working on a program where each item can hold an array of items (i'm making a menu, which has a tree-like structure)
currently i have the items as a list, instead of an array, but I don't feel like I'm using it to its full potential to simplify code. I chose a list over a standard array because the interface (.add, .remove, etc...) makes a lot of sense.
I have code to search through the structure and return the path of the name (i.e. Item.subitem.subsubitem.subsubsubitem). Below is my code:
public class Item
{
//public Item[] subitem; <-- Array of Items
public List<Item> subitem; // <-- List of Items
public Color itemColor = Color.FromArgb(50,50,200);
public Rectangle itemSize = new Rectangle(0,0,64,64);
public Bitmap itemBitmap = null;
public string itemName;
public string LocateItem(string searchName)
{
string tItemName = null;
//if the item name matches the search parameter, send it up)
if (itemName == searchName)
{
return itemName;
}
if (subitem != null)
{
//spiral down a level
foreach (Item tSearchItem in subitem)
{
tItemName = tSearchItem.LocateItem(searchName);
if (tItemName != null)
break; //exit for if item was found
}
}
//do name logic (use index numbers)
//if LocateItem of the subitems returned nothing and the current item is not a match, return null (not found)
if (tItemName == null && itemName != searchName)
{
return null;
}
//if it's not the item being searched for and the search item was found, change the string and return it up
if (tItemName != null && itemName != searchName)
{
tItemName.Insert(0, itemName + "."); //insert the parent name on the left --> TopItem.SubItem.SubSubItem.SubSubSubItem
return tItemName;
}
//default not found
return null;
}
}
My question is if there is an easier way to do this with lists? I've been going back and forth in my head as to whether I should use lists or just an array. The only reason I have a list is so that I don't have to make code to resize the array each time I add or remove an item.