I have the following code which gives me a Stack
containing the folder hierarchy of a path:
var path = @"C:\Folder1\Folder2\Folder3\Folder4\Folder5\FileName.ext";
// String array with an element for each level
var folders = path.Split('\\');
var stack = new Stack<string>();
foreach(var folder in folders)
stack.Push(folder);
var filename = stack.Pop(); // 'FileName.ext'
var parent = stack.Pop(); // 'Folder5'
var grandParent = stack.Pop(); // 'Folder4'
Just out of curiosity, is there a more elegant way to convert the folders
array into a Stack
without the foreach
loop? Something like the (non-existent) following:
var folders = path.Split('\\').Reverse().ToStack();
I look forward to your suggestions!
Stack<T>
has a constructor that accepts IEnumerable<T>
You can use
var stack = new Stack(folders);
Note that this still performs looping, it just does it for you.
Edit: Your code uses a Stack
but your title asks about a Stack<T>
. This is the non-generic version. Make your mind up :p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With