LINQ Query to Fetch Data from XML in Ascending and Descending Order

← PrevNext →

The code snippet in this post is in response to a mail that I have received a few days back from a user, who asked me, how to query and fetch data from an XML file using LINQ in descending Order. I’ll show you how to use both Ascending and Descending properties in an orderBy query using LINQ.

Ascending and Descending orderBy in LINQ C#

Here’s a simple example that I have written to explain the two LINQ orderBy (Order By in Vb) properties, Ascending (low to high) and Descending (high to low). Let us assume I have an XML file with two nodes model and price under a node called base. I have saved data in the XML file in random fashion and I wish to display the result either in descending or ascending order. The orderBy (linq) query will execute and filter using the price node.

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. Copy the data (below) 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 {}
    }
}
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.

← PreviousNext →