Skip to main content

Sort Dictionary Based On Value In Asp.Net And C#.Net | Convert Dictionary into KeyValuePair or KeyValuePair into Dictionary.

In this tutorial i am going to explain about how to sort dictionary object based on value in asp.net and C#.Net or convert unsorted dictionary to sorted dictionary object in C#.Net and VB.Net or Convert Dictionary into KeyValuePair or KeyValuePair into Dictionary.

In my previous article i have explained about Get All Coutries From System.Globalization Namespace , Web Api Model Validation Using Validation Filters , Convert String To Upper,Lower & Title(Proper) Case Using TextInfo Class Build Products Comparision Table/Grid In ASP.Net , Store Custom Objects In Configuration File , Create Simple Mathmatical Captcha In ASP.Net and many articles in ASP.Net,C#.Net,VB.Net,Grid View,Javascript,jQuery,SQL Server and many other topics.

In this tutorial for explaining about how to sort dictionary object based on value in ASP.Net and C#.Net i have created a dictionary object and addede some items into the dictionary object. Then i converted into KeyValuePair object using Dictionary.ToList() method and then using Sort and delegate method i sorted the KeyValuePAir object and then again converted back into Dictionary object before binding it to the dropdownlist.Below is the HTML Markup i used.

HTML Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>Sorting Dictionary By Value</h2>
       <asp:DropDownList ID="ddlCountries" runat="server" Width="200">    
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

Below is the code behind file code.

C#.Net:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Dictionary<string, string> objCountries = new Dictionary<string, string>();
       
        //Adding countries to dictionary in random order
        objCountries.Add("India", "India");
        objCountries.Add("America", "America");
        objCountries.Add("Canada", "Canada");
        objCountries.Add("Britain", "Britain");
        objCountries.Add("New Zealand", "New Zealand");
        objCountries.Add("Nepal", "Nepal");
        objCountries.Add("Myanmar", "Myanmar");
        objCountries.Add("China", "China");
        objCountries.Add("Singapore", "Singapore");

        //Sorting the countries in the dictionary object based on value
        List<KeyValuePair<string, string>> mySortedList = objCountries.ToList();

        mySortedList.Sort(
            delegate(KeyValuePair<string, string> firstPair,
            KeyValuePair<string, string> nextPair)
            {
                return firstPair.Value.CompareTo(nextPair.Value);
            }
        );

        Dictionary<string, string> objSortedCountries = new Dictionary<string, string>();
       
        //Converting KeyValuePair to Dictionary Object
        objSortedCountries = mySortedList.ToDictionary(x => x.Key, x => x.Value);

        //Binding Dictionary Object To DropDownList
        ddlCountries.DataSource = objSortedCountries;
        ddlCountries.DataTextField = "Value";
        ddlCountries.DataValueField = "Key";
        ddlCountries.DataBind();
        //Default Record
        ddlCountries.Items.Insert(0, new ListItem("Select Countries", ""));
    }
}

VB.Net Code:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class Default2
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        Dim objCountries As New Dictionary(Of String, String)()

        'Adding countries to dictionary in random order
        objCountries.Add("India", "India")
        objCountries.Add("America", "America")
        objCountries.Add("Canada", "Canada")
        objCountries.Add("Britain", "Britain")
        objCountries.Add("New Zealand", "New Zealand")
        objCountries.Add("Nepal", "Nepal")
        objCountries.Add("Myanmar", "Myanmar")
        objCountries.Add("China", "China")
        objCountries.Add("Singapore", "Singapore")

        'Sorting the countries in the dictionary object based on value
        Dim mySortedList As List(Of KeyValuePair(Of String, String)) = objCountries.ToList()

        mySortedList.Sort(Function(firstPair As KeyValuePair(Of String, String), nextPair As KeyValuePair(Of String, String)) firstPair.Value.CompareTo(nextPair.Value))

        Dim objSortedCountries As New Dictionary(Of String, String)()

        'Converting KeyValuePair to Dictionary Object
        objSortedCountries = mySortedList.ToDictionary(Function(x) x.Key, Function(x) x.Value)

        'Binding Dictionary Object To DropDownList
        ddlCountries.DataSource = objSortedCountries
        ddlCountries.DataTextField = "Value"
        ddlCountries.DataValueField = "Key"
        ddlCountries.DataBind()
        'Default Record
        ddlCountries.Items.Insert(0, New ListItem("Select Countries", ""))
    End Sub
End Class

If you run the application you will get the below output.
Output of Sort Dictionary Based On Value In Asp.Net And C#.Net | Convert Dictionary into KeyValuePair or KeyValuePair into Dictionary.
SourceCode:
Source Code of Sort Dictionary Based On Value In Asp.Net And C#.Net | Convert Dictionary into KeyValuePair or KeyValuePair into Dictionary.
If you like this article then share with your friends and comment your valuable feedback.. Happy coding..

You May Also Like...

Comments

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     { ...

Puzzles for kids - 12 Days Of Christmas

According to the traditional song, on the first day of Christmas (25th December), my true love sent to me: . A partridge in a pair tree On the second day of Christmas (26th December), my true love sent to me THREE presents: . Two turtle doves . A partridge in a pear tree On the third day of Christmas (27th December and so on) my true love sent to me SIX presents: . Three French hens . Two turtle doves . A partridge in a pear tree This carries on until the the twelfth day of Christmas, when my true love sends me: Twelve drummers drumming Eleven pipers piping Ten lords a-leaping Nine ladies dancing Eight maids a-milking Seven swans a-swimming Six geese a-laying Five gold rings Four calling birds Three French hens Two turtle doves A partridge in a pear tree After the twelve days of Christmas are over, how many presents has my true love sent me altogether? Our Solution: 1 + 3 + 6 + 10 + 15 + 21 + 28 + 36 + 45 + 55 + 66 + 78 = 364 presents Which is really interesting when you think ...

Asp.Net DataTable Manipulation - Add, Update,Delete & Sort DataTable in C#.Net & VB.Net

In the asp.net developer's life it is very common to come across the datatable manipulation. So here i have decided to explain the datatable manipulation like adding records to datatable, editing and updating datatable records,deleting records from datatable based on the condition and finally sorting datatable based on columns.