Home > Blockchain >  How to get max and min value in stack C#
How to get max and min value in stack C#

Time:04-13

How can I get the max and min value in the stack using C#?

I searched about that a lot I didn't find any way that can help me with it.

I'm using Visual Studio and created a form to enter numbers in a stack. But I have no idea how to get the max number and min number in that stack

Can anyone help me with that?

CodePudding user response:

Like this

        // load demo stack
        var s = new Stack<int>();
        s.Push(1);
        s.Push(2);
        s.Push(3);

now

        var minn = s.Min(); <<<==== get min
        var maxx = s.Max(); <<<=== get max

explanation

A Stack is an IEnumerable type so all LINQ extensions can be used on it

PS - note that you should not use the old Stack class, use Stack<int>; your comment suggested that you were using Stack

  • Related