Effortlessly Fetch and Sort XML Data Using LINQ: Ascending and Descending Order Queries in C# and VB.NET

← PrevNext →

This code snippet responds to an inquiry I received recently about querying and fetching data from an XML file using LINQ in descending order. In this guide, I will show you how to use both ascending and descending properties in an OrderBy query with LINQ. You will learn how to efficiently sort XML data and fetch the desired results using LINQ's powerful querying capabilities.
See this demo

Ascending and Descending orderBy in LINQ C#

Here's a straightforward example to illustrate the use of the LINQ OrderBy properties, Ascending (low to high) and Descending (high to low). Imagine an XML file with two nodes: model and price, nested under a base node. The data in the XML file is saved in a random order, and our goal is to display the results in either ascending or descending order based on the price node. By leveraging the OrderBy query in LINQ, we can efficiently sort and filter the data using the specified price values.

The XML Data

Create a data folder in the root directory, create an XML file, name it datafile.xml, and save the file in the "data" folder. Below is a Sample XML data. Copy and save the data in the file.

<?xml version="1.0"?>
<!--   Last edited by Arun Banik @ https://www.encodedna.com   -->
<list>
  <base>
    <model>Hyundai</model>
    <price>51000</price>
  </base>
  <base>
    <model>Volkswagen</model>
    <price>25000</price>
  </base>
  <base>
    <model>Chevrolet</model>
    <price>32000</price>
  </base>
  <base>
    <model>Mercedes-Benz</model>
    <price>76000</price>
  </base>
  <base>
    <model>BMW-Coupe</model>
    <price>46000</price>
  </base>
  <base>
    <model>Audi-Q7</model>
    <price>88000</price>
  </base>
  <base>
    <model>Lamborgini</model>
    <price>55000</price>
  </base>
  <base>
    <model>Jaguar</model>
    <price>36000</price>
  </base>
</list>
The Markup

In the markup section, I have two buttons that will fetch data from XML and a <div> element to show the result. Simply add the below markup in your web page, inside the <body> tag.

<div style="width:400px;font:15px Verdana;">
    <p><button id="low" onserverclick="sortlow" runat="server">Low to High</button></p>
    <p><button id="high" onserverclick="sorthigh" runat="server">High to Low</button></p>

    <%--SHOW THE FILTERED RESULT IN THE THE DIV.--%>
    <div id="basepack" runat="server" style="width:auto;margin:0;"></div>
</div>
Code behind (C#)
using System;
using System.Collections.Generic;   // FOR IEnumerable.

using System.Linq;                  // FOR Descendants().
using System.Xml.Linq;              // FOR XDocument, XElement.

using System.Web.UI.HtmlControls;

public partial class SiteMaster : System.Web.UI.MasterPage
{
    protected void sortlow(object sender, EventArgs e)
    {
        sortby("Ascending");
    }
    protected void sorthigh(object sender, EventArgs e)
    {
        sortby("Descending");
    }

    private void sortby(string sSortOrder)
    {
        try {
            // LOAD XML DOCUMENT.
            var xml_Doc = XDocument.Load(Server.MapPath("~/data/datafile.xml"));

            IEnumerable<XElement> search = null;

            // *** FIND CAR MODEL BY PRICE IN ASCENDING AND DESCENDING ORDER.
            if (sSortOrder.Trim() == "Ascending") {
                search = (from xFi in xml_Doc.Descendants("base") 
                    orderby xFi.Element("price").Value ascending
                    select xFi);
            } else {
                search = (from xFi in xml_Doc.Descendants("base") 
                    orderby xFi.Element("price").Value descending
                    select xFi);
            }

            // NOW DISPLAY THE RESULT.
            if ((search != null)) {
                basepack.InnerHtml = "";

                foreach (XElement result in search) {
                    HtmlGenericControl divContainer = new HtmlGenericControl("div");

                    divContainer.InnerHtml = "<div>" + 
                        "<div style='float:left;width:50%;'>Model: " + result.Element("model").Value + "</div>" + 
                        "<div>Price $: " +  result.Element("price").Value + "</div>" + 
                        "</div>";

                    basepack.Attributes.Add("style", "position:relative;text-align:left;");
                    basepack.Controls.Add(divContainer);
                }
            }
        } catch (Exception ex) {
        } finally {}
    }
}
See this demo
Code behind (Vb)
Option Explicit On

Partial Class Site
    Inherits System.Web.UI.MasterPage

    Protected Sub sortlow(ByVal sender As Object, ByVal e As EventArgs)
        sortby("Ascending")
    End Sub
    Protected Sub sorthigh(ByVal sender As Object, ByVal e As EventArgs)
        sortby("Descending")
    End Sub

    Private Sub sortby(ByVal sSortOrder As String)
        Try
            ' LOAD XML DOCUMENT.
            Dim xml_Doc = XDocument.Load(Server.MapPath("~/data/datafile.xml"))

            Dim search As IEnumerable(Of XElement)

            ' *** FIND CAR MODEL BY PRICE IN ASCENDING AND DESCENDING ORDER.
            If Trim(sSortOrder) = "Ascending" Then
                search =
                (From xFi In xml_Doc.Descendants("base") _
                    Select xFi Order By xFi.Element("price").Value Ascending)
            Else
                search =
                (From xFi In xml_Doc.Descendants("base") _
                    Select xFi Order By xFi.Element("price").Value Descending)
            End If

            ' NOW DISPLAY THE RESULT.
            If Not search Is Nothing Then
                basepack.InnerHtml = ""

                For Each result As XElement In search
                    Dim divContainer As New HtmlGenericControl("div")

                    divContainer.InnerHtml =
                        "<div>" & _
                            "<div style='float:left;width:50%;'>Model: " & result.Element("model").Value & "</div>" & _
                            "<div>Price $: " & FormatNumber(result.Element("price").Value, "0.00") & "</div>" & _
                        "</div>"

                    basepack.Attributes.Add("style", "position:relative;text-align:left;")
                    basepack.Controls.Add(divContainer)
                Next
            End If
        Catch ex As Exception
        Finally
        End Try
    End Sub
End Class

That’s it. Using this code, you can now filter and extract data from XML in both descending and ascending order.

See this demo

← PreviousNext →