Introduction: Sorted Dictionary in C#.Net

In this post, we will learn about Sorted Dictionary in C#.Net with an example. SortedDictionary keeps its keys always sorted. It allows you to avoid sorting the keys on your own.It has advantages if you want a sorted lookup table.


Description:

In my previous posts I have explained various topics like Collections in C#SortedSet in C#.Net,Stack in C#,Dictionary in C#.Net,Queue in C#.Net,LinkedList in C#.Net. Now in this post, I will explain about Dictionary in C#.Net with appropriate example.

Methods:

1. Add()

This method is used to add the key/value pair to the dictionary.

2. ContainKey()

This method is used to determines whether the SortedDictionary<TKey, TValue> contains an element with the specified key or not. If yes then return true else return false.

3. ContainValue()

This method is used to determines whether the SortedDictionary<TKey, TValue> contains an element with the specified value or not and returns true if the value exists.

4. Remove()

This method is used to removes the element with the specified key from the SortedDictionary<TKey, TValue>.

5. Clear()

This method is used to removes all elements from the SortedDictionary<TKey, TValue>.

Now, Create Console Application in Visual Studio and write below line of code.

using System;
using System.Collections.Generic;

namespace ConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a SortedDictionary with site as a string and Int16 value pair
            SortedDictionary<string, Int16> SiteList = new SortedDictionary<string, Int16>();
            SiteList.Add("DotNetK.com", 10);
            SiteList.Add("Live24u.com", 30);
            SiteList.Add("w3school.com", 15);

            // Read all data
            Console.WriteLine("Site List");

            foreach (KeyValuePair<string, Int16> site in SiteList)
            {
                Console.WriteLine("Key: {0}, Value: {1}",
                    site.Key, site.Value);
            }
            Console.ReadKey();
        }
    }   
}

Sorted Dictionary in C#.Net

Sorted Dictionary in C#.Net


I hope you got an idea about Sorted Dictionary in C#.Net.
I would like to have feedback from my blog readers.
Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website