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

An Overview of SortedList Functionality using Csharp and ASP.NET

In this article you will see how the SortedList works. SortedList is just like a list, but keeps the key always sorted.

Introduction:

SortedList work in same way as List works, the difference is that it keeps the keys always sorted. The SortedList provide binary search to search a data without writing whole code for search.

This article will cover the following topics:

  1. SortedList - Add Item
  2. SortedList - Delete Item
  3. SortedList - Search by Key
  4. SortedList - Search by Value
  5. SortedList - Display Data
  6. SortedList - Other Functionality

Initial UI and SortedList with Month Data

Figure 1: Initial UI and SortedList with Month Data

ASP.NET Script:

ASP.NET script is used to properly demonstrate the SortedList functionality. The below script have the following items:

  1. ASP.NET TextBox Controls
  2. ASP.NET Label Controls
  3. ASP.NET Buttons Controls

Listing 1: ASP.NET Script for SortedList Demonstration

<head runat="server">
    <title>MrBool.com - SortedList Tutorial</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        ListItem:
        <asp:TextBox ID="txtListKey" runat="server"></asp:TextBox> 
        <asp:TextBox ID="txtListValue" runat="server"></asp:TextBox>
        <br />
        <br />
        Message:
        <asp:Label ID="lblDisplay" runat="server" Text=""></asp:Label>
        <br />
        <br />
        SortedList State:
        <asp:Label ID="lblSortedListState" runat="server" Text=""></asp:Label>
        <br />
        <br />
         <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
         <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
         <asp:Button ID="btnSearchbyKey" runat="server" Text="Search by Key" OnClick="btnSearchbyKey_Click" />
         <asp:Button ID="btnSearchbyValue" runat="server" Text="Search by Value" OnClick="btnSearchbyValue_Click" />
    </div>
    </form>
</body> 

C# Code:

C# provide a SortedList class and methods to handle the operations of SortedList. Lets start with including the namespace for this.

using System;
using System.Collections.Generic;

Now create the SortedList by

static SortedList<int, string> MonthSortedList; 

Now initialize it by

MonthSortedList = new SortedList<int, string>(); 

The above initializations says that the SortedList is type of , it means key is type of int and value is type of string.

Also you have to load some initial data on page load to perform some operation:

Listing 2: SortedList - Initial Data

           //add the items in sortedlist
            MonthSortedList.Add(1, "Jan");
            MonthSortedList.Add(2, "Feb");
            MonthSortedList.Add(3, "Mar");
            MonthSortedList.Add(4, "Apr");
            MonthSortedList.Add(5, "May");
            MonthSortedList.Add(6, "Jun"); 

SortedList - Add Item:

Similar to other collection classes SortedList also use Add() method to add the key and value pair. Just pass the both the pairs and and will be added at sorted location.

Add Item - A Key, Value Pair Added

Figure 2: Add Item - A Key, Value Pair Added (12, “Dec”)

Listing 3: SortedList - Add Item Source Code

protected void btnAdd_Click(object sender, EventArgs e)
    {
        int intKey;
        Int32.TryParse(txtListKey.Text, out intKey);

        if (intKey >= 0 && txtListValue.Text.Trim() != "")
        {
            if (!MonthSortedList.ContainsKey(intKey))
            {
                MonthSortedList.Add(intKey, txtListValue.Text.Trim());

                lblDisplay.Text = "SortedList Item Added";
            }
            else
            {
                lblDisplay.Text = "SortedList - Key Already Exist";
            }
        }
        else
        {
            lblDisplay.Text = "SortedList - Please Enter an Item to Add";
        }
        RenderDetails();
    }
 

SortedList - Delete Item:

To delete an item from SortedList use the Remove() method. Pass the key in this method and it will delete the item from SortedList. After deletion the List values will be sorted automatically.

Note that for deletion you can use RemoveAt() method also. This method delete the items by index.

Delete Item

Figure 3: Delete Item - (2,”Feb”) is removed from SortedList

Listing 4: SortedList - Delete Item Code

protected void btnDelete_Click(object sender, EventArgs e)
    {
        int intKey;
        Int32.TryParse(txtListKey.Text, out intKey);

        if (intKey >= 0)
        {
            if (MonthSortedList.ContainsKey(intKey))
            {
                MonthSortedList.Remove(intKey);

                //MonthSortedList.RemoveAt(1);
                lblDisplay.Text = "SortedList Item Deleted";
            }
            else
            {
                lblDisplay.Text = "Item Not Found.";
            }
        }
        else
        {
            lblDisplay.Text = "SortedList - Please Enter an Item to Delete";
        }
        RenderDetails();
    }
 

SortedList - Search by Key:

SortedList provide search by both key also. To search by key use ContainsKey() method and pass the key in it.

Search by Key

Figure 4: Search by Key - The ‘4 -Apr’ found in SortedList key

Listing 5: SortedList - Search by Key - Code

protected void btnSearchbyKey_Click(object sender, EventArgs e)
    {
        int intKey;
        Int32.TryParse(txtListKey.Text, out intKey);

        if (intKey > -1)
        {
            if (MonthSortedList.ContainsKey(intKey))
            {
                lblDisplay.Text = "SortedList Item Found";
            }
            else
            {
                lblDisplay.Text = "SortedList Item Not Found.";
            }
        }
        else
        {
            lblDisplay.Text = "Please Enter an Item to Search";
        }
        RenderDetails();
    }
 

SortedList - Search by Value:

Use ContainsValue to search a value in the SortedList. This method remove extra effort to loop through all the values and search an item.

Search by Value found in SortedList

Figure 5: Search by Value - The value ‘5-May’ found in SortedList

Listing 6: SortedList - Search by Value - Code

protected void btnSearchbyValue_Click(object sender, EventArgs e)
    {
        if (txtListValue.Text.Trim() != "")
        {
            if (MonthSortedList.ContainsValue(txtListValue.Text.Trim()))
            {
                lblDisplay.Text = "SortedList Item Found";
            }
            else
            {
                lblDisplay.Text = "SortedList Item Not Found.";
            }
        }
        else
        {
            lblDisplay.Text = "Please Enter an Item to Search";
        }
        RenderDetails();
    }
 

SortedList - Display Data:

The foreach loop is best idea to loop through the items of SortedList and display in an ASP label.

Listing 7: SortedList - Loop through items and display data on ASP page

private void RenderDetails()
    {
        lblSortedListState.Text = "";

        foreach (KeyValuePair<int, string> pair in MonthSortedList)
        {
            lblSortedListState.Text += "," + pair.Key + ":" + pair.Value;
        }
        lblSortedListState.Text = lblSortedListState.Text.TrimStart(',');
    } 

SortedList - Other Functionality:

Apart from above functionalities C# SortedList provide some more common functions.

  • IndexOfKey: Returns the index of a given key.
  • IndexOfValue: Returns the index of a given value.
  • Count: Returns the item count
  • Clear(): Clear the items of SortedList
  • Capacity : Returns the capacity of SortedList.

Listing 8: SortedList - Other operation

 
private void OtherFunctionality()
    {
        int intKey = 0;
        Int32.TryParse(txtListKey.Text, out intKey);

        lblDisplay.Text = " Get the index of Key: " + MonthSortedList.IndexOfKey(intKey);

        lblDisplay.Text = " Get the index of Value: " + MonthSortedList.IndexOfValue(txtListValue.Text.Trim());

        //Clear all the items of SortedList
        MonthSortedList.Clear();

        lblDisplay.Text = " Count of All the Items of SortedList: " + MonthSortedList.Count;

        lblDisplay.Text = " Capacity of All the Items of SortedList: " + MonthSortedList.Capacity;

    }

Conclusion:

The SortedList is useful on case by case basis, So first find the requirement and then decide which collection to use . I covered almost all common fetures, Please comment here in case you have any queries or doubts.



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