I'm trying to write a program which requires nesting an undetermined number of loops. I am completely confused by how I can do this without hard coding the actual loops. To say the entire purpose of the program is pretty long and complicated, so I will give a simple example of what I am trying to do:
Let's say I have a class called box. This class contains a string "description" as well as some other attributes. I load a file which fills a random number of List<boxes> When I'm done, I have n List<boxes> loaded. Now let's say one of the boxes in the lists has a description containing "key". Another box, probably but not necessarily in a different list, contains a description with "lock". I need to iterate through every pair of boxes to compare each one and see which gets a key-lock combination.
If I knew that there were, for example, 3 List<box>, I would just code 3 nested for loops and iterate that way. However, I have absolutely no idea how to structure the code where the number of lists is a variable. The only way I can think of is to have a program which codes another .cs file containing the required number of loops, linking to visual studio, and executing it, but that seems way too complicated. Is there another way to do this?
You define each list in your code. You have to, otherwise how would you reference it? The question doesn't make a lot of sense. If you have a list of <something> and something contains lists and so on you just loop through them all.
Sometimes recursion helps answer questions like yours. What you're describing sounds like a tree-like structure (by the way, posting a diagram wouldn't hurt, if you can make one). Get a text book on data structures and look at the algorithms for traversing trees. Trees have the same issue - you don't necessarily know at design time how deep the tree is.
Last edited by kender_a; January 23rd, 2011 at 05:07 PM.
Kender is right; I didn't get that from your explanation, but if your data is structured like a tree, recursion simplifies things a lot. Anything you can do with recursion you can do with iterative loops, but the former really shines when parsing tree like data and using loops in this case is difficult and makes the code hard to follow.