Mark Bell
Mark Bell

Reputation: 29755

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

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!

Upvotes: 16

Views: 12582

Answers (3)

Botz3000
Botz3000

Reputation: 39620

If you really want a ToStack() method, you could create an extension method:

public static class Extensions {
    public static Stack<T> ToStack(this IEnumerable<T> sequence) {
        return new Stack<T>(sequence);
    }
}

Or, as the others noted, you could use the constructor that accepts an IEnumerable<T> for it.
It's a matter of personal preference I guess.

Upvotes: 2

Rawling
Rawling

Reputation: 50144

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

Upvotes: 8

Jakub Konecki
Jakub Konecki

Reputation: 46008

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

Upvotes: 36

Related Questions