Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, is there a way to convert an array to a Stack<T> without looping?

Tags:

c#

.net

c#-4.0

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!

like image 249
Mark Bell Avatar asked Dec 19 '12 10:12

Mark Bell


2 Answers

Stack<T> has a constructor that accepts IEnumerable<T>

like image 189
Jakub Konecki Avatar answered Sep 27 '22 20:09

Jakub Konecki


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

like image 44
Rawling Avatar answered Sep 27 '22 22:09

Rawling