Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with Stack Data Structure in Csharp and ASP.NET

In this article we wil cover some features about Stack Data Structure, just like: Push, Pop, Search and display.

Introduction:

Stack data structure work Last in First out basis (LIFO). Its means that the last inserted item will come out first. The Stacks are useful while solving some complex problems and recursion.

This article will cover the following topics:

  1. Push into Stack
  2. Pop from Stack
  3. Search in Stack
  4. Display Stack Data
  5. Stack -Other Functionality

 Initial UI and Stack Data

Figure 1: Initial UI and Stack Data

ASP.NET Code:

The below ASP.NET code is used in this tutorial to demonstrate the functionality. This script includes some textbox , labels and buttons.

Listing 1: ASP.NET Script for Stack Demonstrate

<head runat="server">
    <title>MrBool.com Tutorial - Stacks</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Item: <asp:TextBox ID="txtItem" runat="server"></asp:TextBox>
    <br />
    <br />
    
        Message: <asp:Label ID="lblMSG" runat="server" Text=""></asp:Label>
        <br />
        <br />
        Stack State: <asp:Label ID="lblStack" runat="server" Text=""></asp:Label>
        <br />
        <br />
        <asp:Button ID="btnPush" runat="server" Text="Push" onclick="btnPush_Click" />
         <asp:Button ID="btnPop" runat="server" Text="Pop" 
            onclick="btnPop_Click" />
         <asp:Button ID="btnSearch" runat="server" Text="Search" 
            onclick="btnSearch_Click" />
         </div>
    </form>
    
</body>

C# Code:

Lets start with C# code, You have to include the following namespaces to properly use the stack collections.

Listing 2: Including stack collections

using System;
using System.Collections.Generic;

Now you have to create stack object and initialize it . The below code snippet will create a NumberStack object and then initialize it.

Listing 3: Creating NumberStack Object

static Stack<int> NumberStack;
NumberStack = new Stack<int>();

Push into Stack:

Push and pop are two common operations in stack. Push means put the item in stack collection and pop means remove the item from stack collection.

This tutorial is using a int stack, so you can only insert int values. If you want to insert a string then define stack with

Listing 4: Using a Stack

Stack<int> 

Also you can have a stack of class objects.

Push Operation - 120 Pushed in stack

Figure 2: Push Operation - 120 Pushed in stack

Listing 5: Stack - Push Operation

protected void btnPush_Click(object sender, EventArgs e)
    {
        if (txtItem.Text.Trim() != "")
        {
            int StackItem;
            int.TryParse(txtItem.Text, out StackItem);
            NumberStack.Push(StackItem);

            lblMSG.Text = StackItem + " Pushed in Stack.";
            DisplayStackState();
        }
        else
        {
            lblMSG.Text = "Enter an Item.";
        }

    } 

Pop from Stack:

The Stack collection class provide method pop() to remove elements from the top of stack. Note that we are using DisplayStackState(); method to display the stack state after every operation.

Pop Operation - 120 removed from Stack

Figure 3: Pop Operation - 120 removed from Stack

Listing 6: Stack - Pop Operation

protected void btnPop_Click(object sender, EventArgs e)
    {        
        if (NumberStack.Count > 0)
        {
            int StackItem = NumberStack.Pop();
            lblMSG.Text = StackItem + " removed from Stack.";
            DisplayStackState();
        }
        else
        {
            lblMSG.Text = "Stack is Empty.";
        }
    } 

Search in Stack:

C# stack class also provide a Contains() method to search for a particular item and return the result in true or false.

Search Operation - 100 found in Stack

Figure 4: Search Operation - 100 found in Stack

Listing 4: Stack - Search Operation

protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtItem.Text.Trim() != "")
        {
            int StackItem;
            int.TryParse(txtItem.Text, out StackItem);

            bool Result = NumberStack.Contains(StackItem);
            if(Result)
                lblMSG.Text = StackItem + " item found in Stack.";            
            else
                lblMSG.Text = StackItem + " item not found in Stack."; 
        }
        else
        {
            lblMSG.Text = "Enter an Item.";
        }
    } 

Display Stack Data:

To display stack data, we are having a method. In this we are looping through each item of stack. The stack is also a collection so we can use it with foreach loop.

Listing 5: Stack - Loop through items and display data

private void DisplayStackState()
    {        
        foreach (int StackItem in NumberStack)
        {
            lblStack.Text += ", " + StackItem;
        }

        lblStack.Text = lblStack.Text.TrimStart(',');
    } 

Stack -Other Functionality:

Stack class provide some other functionality, Some of these functionality are demonstrated in below method. If want you want to use any of the below functionality just un-comment that line and call it from the page load.

If you are using a int stack then you can use the math operations like Average, Max, Min , sum etc. You can also clear the stack and count the number of items in Stack.

The stack class provide functionality to copy stack items in array.

Listing 6: Stack - Other operation

private void OtherFunctionality()
    {
        //Uncomment to use any functionality

        //lblMSG.Text = " Average of All the Items of Stack: " + NumberStack.Average();

        //lblMSG.Text = " Max of All the Items of Stack: " + NumberStack.Max();

        //lblMSG.Text = " Min of All the Items of Stack: " + NumberStack.Min();

        //lblMSG.Text = " Sum of All the Items of Stack: " + NumberStack.Sum();

        ////Clear all the items of Stack
        //NumberStack.Clear();

        //lblMSG.Text = " Count of All the Items of Stack: " + NumberStack.Count;

        //int[] tempArray =  NumberStack.ToArray();

        //int[] newArray = new int[100];
        //NumberStack.CopyTo(newArray, 2);
    } 

Conclusion:

The stack data structure is very useful for some operations like recursion. C# provide it easy to use without any implementation. So use it whenever it is required and efficient.

Hope this tutorial is useful to you.



I am having total 7+ years of experience in developing applications using C#, VB.NET, ASP.NET, Silverlight, WCF, SQL Server and Oracle. I am holding a M.Tech degree in Intelligent systems. For more information, visit my Linkedin p...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login