Menu ▼

Previous Next

LINQ to XML where condition between to filter records with order by specific column :

In this example we will apply where condition to Salary column and get the employee details who are having salary between 20,000 and 50,000 and order by Salary ascending.

Example :

Design :

<div>

    <asp:GridView ID="gvXML" runat="server" GridLines="Both" CellPadding="5">

    </asp:GridView>

</div>


Code Behind (C#) :

System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Parse(@"

<Employees>

    <Employee>

        <Name>Thomas</Name>

        <Designation>Executive</Designation>

        <Department>Accounts</Department>

        <Salary>5000</Salary>

    </Employee>

    <Employee>

        <Name>Wills</Name>

        <Designation>Manager</Designation>

        <Department>Accounts</Department>

        <Salary>24000</Salary>

    </Employee>

    <Employee>

        <Name>Brod</Name>

        <Designation>Manager</Designation>

        <Department>Finance</Department>

        <Salary>28000</Salary>

    </Employee>

    <Employee>

        <Name>Smith</Name>

        <Designation>Analyst</Designation>

        <Department>Finance</Department>

        <Salary>21000</Salary>

    </Employee>

</Employees>

");

var res = from emp in xdoc.Root.Elements()

            where 20000 < (decimal)emp.Element("Salary") &&

            (decimal)emp.Element("Salary") < 25000

            orderby (decimal)emp.Element("Salary") ascending

            select new

            {

                EmployeeName = emp.Element("Name").Value,

                Designation = emp.Element("Designation").Value,

                Department = emp.Element("Department").Value,

                Salary = emp.Element("Salary").Value

            };

gvXML.DataSource = res;

gvXML.DataBind();


Output :
EmployeeNameDesignationDepartmentSalary
SmithAnalystFinance21000
WillsManagerAccounts24000
Previous Next




Search dotnetlearners.com