John
John

Reputation: 127

Pop range of elements in Stack

Hi guys i need a small help about Stack.Pop() function. As I know stack can pop out elements one by one, but I need more than one element to pop out. For example, I have 5 elements in stack (4,3,2,1,0) and now I want to pop out first 3 or 2 elements till stack index reaches 1 or 2. by now I have "for" cycle which is not working correctly:

for(var i = stack.Count - 1; i >= 0; i--)
{
    stack.Pop();
}

Can someone please help me out, to let him pop out certain range of elements? Thanks!

Upvotes: 1

Views: 5851

Answers (4)

Shahar Shokrani
Shahar Shokrani

Reputation: 8752

You can use TryPopRange of the ConcurrentStack class.

Example:

var stack = new ConcurrentStack<int>(new[] { 1, 2, 3, 4, 5 });
var resultPop = new int[2]; //Assume that we want to pop only 2 items.
int startIndex = 0;
int endIndex = 1;

// The TryPopRange will pop 2 items from stack into resultPop.
if (stack.TryPopRange(resultPop, startIndex, endIndex) >= 1) //It returns the number of  popped item.
{
    Console.WriteLine($"This items has been popped: {string.Join(",", resultPop)}");
}

Upvotes: 2

Finickyflame
Finickyflame

Reputation: 863

You could also create an Extension Method:

public static class Extensions
{
    public static List<T> PopRange<T>(this Stack<T> stack, int amount)
    {
        var result = new List<T>(amount);
        while (amount-- > 0 && stack.Count > 0)
        {
            result.Add(stack.Pop());
        }
        return result;
    }
}

And use it where you want:

var stack = new Stack<int>(new[] { 1, 2, 3, 4, 5 });

var result = stack.PopRange(3);

// result: { 5, 4, 3 }
//  stack: { 2, 1}

Upvotes: 5

juharr
juharr

Reputation: 32286

If you want to pop until the stack is a certain size just use

while(stack.Count > desiredCount)
    stack.Pop();

If you want to pop a certain number of items then just use

for(int i=0; i < numberOfItemsToPop && stack.Count > 0; i++)
    stack.Pop();

Upvotes: 4

Dave Bish
Dave Bish

Reputation: 19646

You can do something like this using a simple while loop:

var stack = new Stack<int>(new[]{ 4, 3, 2, 1, 0 });

var numberToPop = 3;
while(numberToPop > 0 && stack.Count > 0)
{
    numberToPop--;
    stack.Pop();
}

Upvotes: 2

Related Questions