There are two ways I can separate out the loop control logic and have the
loop just return the directories for the caller to process.
Firstly, I could use the loop to build a list like this,
instantiate the list,
and then add items to the list as I discover them in the loop.
That can be a good solution if I know that I will always
want to process the items as a list,
but it does incur some overhead to construct the list.
More generally, in most cases,
I would stay simple and just return an enumerable sequence like so.
I've added a method called EnumParentNames,
while no need to construct a list, I just return each item with yield return.
If that looks a bit weird to you having the yield return inside the loop,
rest assured that it's fine.
That's exactly how yield return is designed to work.
It passes the item back to the caller and leaves the code
that's executing the loop waiting to continue the loop as
soon as the next item is requested.
Now you have a well‑designed loop to generate the sequence of directory names.
So now I will return to the main program and change the code to
reflect that it's now the main program that is responsible for
displaying the returned results.
There are a few things to notice here.
Because the method is returning an enumerable sequence,
you use a foreach loop to process it and that's great.
You can see I have two loops now where I only had one before,
but that's because each loop is now only performing one task.
The question remains, how can you get the results in the correct order?
That is now easy.
You can just turn to link and say foreach folder in folders.reverse,
which will reverse the enumerated order.
Now if I run that, you have the directories listed in descending order.
Turning back to the while loop,
the other great advantage of returning an enumerable sequence is that
you're leaving it up to the caller to decide how many items it wants and
to stop when it has all the data it needs.
In this case, you do want all the items,
but if for some reason the caller didn't want the entire set of directories,
the while loop wouldn't waste time getting the unwanted ones.
So the takeaway here is that if your loop requires some
nontrivial logic to do whatever iteration it's doing,
it's often good practice to design the loop to just
return the iteration results, for example,
as a sequence and lets the caller deal with processing the results.
It is situational dependence though. What I'm suggesting here is a guideline, not a cast iron rule.