Here are two examples :
I have an array with 3 items : Universe, planet and Continent I want to use a foreach loop like this :
foreach(var universe in Universe)
{
foreach(var planet in Planet)
{
foreach(var continent in Continent)
{
// here comes my code
} } }
In this case the array contains 3 elements and therefore I need 3 foreach statements.
Now lets say that I add 2 extra items to the array (Country and State) There would have to be 5 foreach loops.
But what if the array contains 600 items : then I would need to write 600 foreach statements...
So how can this be programatically solved?
If you have one array with three items in it, then in order to enumerate through the items you should only need one foreach loop.
List<Object> items = new List<Object> { Universe, Earth, Continent };
foreach (var item in items) { ... }
You would only need to write additional nested foreach loops if the objects contained by the outer array each themselves implemented IEnumerable
, and you needed to enumerate these as well. Without seeing the problem that you are trying to solve, it is hard to make a recommendation. But I think that the assumption that you need to have nested foreach
structures is incorrect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.