0% found this document useful (0 votes)
53 views48 pages

Lesson9 Linq 2019

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 48

Linq to object

The acronym LINQ stands for Language Integrated Query. Microsoft’s query
language is fully integrated and offers easy data access from in-memory objects

The following illustration shows a LINQ to Objects query operation that


performs no transformations on the data. The source contains a sequence of
strings and the query output is also a sequence of strings.

int[] numbers = { 5, 10, 8, 3, 6, 12};

//Query syntax:
IEnumerable<int> numQuery1 =
from num in numbers
where num % 2 == 0
orderby num
select num;

//Method syntax:
IEnumerable<int> numQuery2 = numbers.Where(num =>
num % 2 == 0).OrderBy(n => n);

foreach (int i in numQuery1)


{
response.Write(i + " ");
}

foreach (int i in numQuery2)


{
response.Write(i + " ");
}
}
}
/*
Output:
6 8 10 12
6 8 10 12
*/

Example 1

var colours = new string[] { "Red", "Orange", "Yellow", "Green", "Blue", "Indigo",
"Violet" };
 
var longNames = colours.Where(c => c.Length >= 5);
 
foreach(string s in longNames)
{
    Response.WriteLe(s);
}
 
/* OUTPUT in browser
 
Orange
Yellow
Green
Indigo
Violet
 
*/
Another example

var query = from str in coulors


where str[0] == 'R'
select str;

THE OUTPUT ONLY

Red

 perform aggregation operations are listed in the following section.

List<int> grades = new List<int> { 78, 92, 100, 37, 81 };

double average = grades.Average();\\‫القائمه‬ ‫معدل ارقام‬


int numberOfgrades = grades.Count(); // ‫كم رقم بالمجموعه‬
long maxgrade= grades.Max();// ‫اكبر عنصر‬
float?[] points = { null, 0, 92.83F, null, 100.0F, 37.46F,
81.1F };

float? sum = points.Sum();

Take operator example


int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

IEnumerable<int> topThreeGrades =
grades.OrderByDescending(grade => grade).Take(3);

result: /*

This code produces the following output:

The top three grades are:


98
92
85
*/

TakeWhile operator
string[] fruits = { "apple", "banana", "mango", "orange",
"passionfruit", "grape" };

IEnumerable<string> query =
fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);

foreach (string fruit in query)


{
response.WriteLe(fruit+"<br/>");
}

/*
‫ا معناها اطبع الفواكه الى ان تصل كلمه‬
orange
This code produces the following output:
apple
banana
mango
*/

Example 2

The following example creates a sequence with large number of int values:

internal static void MaxRange()


{
IEnumerable<int> range = Enumerable.Range(1, int.MaxValue); // Define query.

internal static void Repeat()


{
IEnumerable<string> repeat = Enumerable.Repeat("*", 5); // Define query
ListBox1.DataSource = repeatN; // Execute query. list of * * * * *
Page.DataBind() ;
}

output

Example of list of objects


class Department
{
public int DepartmentId { get; set; }
public string Name { get; set; }
}
protected void Button2_Click(object sender, EventArgs e)
{

List<Department> departments = new List<Department>();

departments.Add(new Department { DepartmentId = 1, Name = "Account" });


departments.Add(new Department { DepartmentId = 2, Name = "Sales" });
departments.Add(new Department { DepartmentId = 3, Name = "Marketing" });

var departmentList = from d in departments


select d.Name;

ListBox1.DataSource = departmentList; /
Page.DataBind();
}

Output is:

Example 4
The following code example demonstrates how the standard query operators
can be used to obtain information about a sequence.:

string sentence = "the quick brown fox jumps over the lazy dog";
// Split the string into individual words to create a collection.
string[] words = sentence.Split(' ');

// Using query expression syntax.


var query = from word in words
select word;
output is:
LINQ to SQL
The following illustration shows a LINQ to SQL query operation that performs
a simple transformation on the data. The query takes a sequence
of Customerobjects as input, and selects only the Name property in the result.
Because Name is a string, the query produces a sequence of strings as output.
The following illustration shows a slightly more complex transformation.
The select statement returns an anonymous type that captures just two members of the
original Customer object.
Binding the DataList Control using LINQ to SQL

Drag and drop a DataList control into our ASPX page from the data
tab of Visual studio toolbar. In order to display data with DataList
control, we need to first provide an ItemTemplate and
HeaderTemplate with the structure of the data display. I have used
tabular view in this article. Refer the below code.
 
Next, we can query the database using LINQ query and bind the
DataList control.
Refer the code below,
 
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindEmp();
    }
    public void BindEmp()
    {
EmployeesDataClassesDataContext dbproducts = new
productsDataClassesDataContext();
var LINQQuery = from product in dbproducts.productlists
                        select product;
        DataList1.DataSource = LINQQuery;
DataList1.DataBind();
    }
Execute the application. You can see the products data populated in the DataList
control. Refer the below figure.
I have specified the Header style and Alternate row style to apply the style and hence
you can the see the colors.

1. <html>  
2. <head runat="server">  
3.     <title>DataList</title>  
4.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1
.0/css/bootstrap.min.css">  
5.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
"></script>  
6.     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.
min.js"></script>  
7.     <style>  
8.         .productList {  
9.             border: 1px solid #6c757d;  
10.             margin-bottom: 10px;  
11.             padding: 15px;  
12.             border-radius: 3px;  
13.         }  
14.     </style>  
15. </head>  
16. <body>  
17.     <form id="form1" runat="server">  
18.         <div class="container py-4">  
19.             <h5 class="text-center text-uppercase">DataList control in asp.net</h5
>  
20.             <asp:DataList ID="DataList1" runat="server" CssClass="row">  
21.                 <ItemTemplate>  
22.                     <div class="row productList">  
23.                         <div class="col-4">  
24.                             <img alt="" width="250" src='<%#Eval("ProductImage")
%>' />  
25.                         </div>  
26.                         <div class="col-8">  
27.                             <h4><%#Eval("ProductName")%></h4>  
28.                             <h6><%#Eval("ProductPrice")%></h6>  
29.                             <div>  
30.                                 <%#Eval("ProductDescription")%>  
31.                             </div>  
32.                         </div>  
33.                     </div>  
34.                 </ItemTemplate>  
35.             </asp:DataList>  
36.         </div>  
37.     </form>  
38. </body>  
39. </html>  

The result page bellow:



Introduction to Linq

 Advantage and Disadvantage of LINQ:-

 Creating a LINQ to SQL Application

 Creating a LINQ to Object Application

 Creating a LINQ to XML Application

 Creating a LINQ to Sample Extension Method

 Type filtering

 Using sorting operators

 Using Join clause

 Using the Grouping operator

 Using the Aggregate operators

 Using the Generation operator

 Using the ZIP operator

 Creating a Simple PLINQ Query

 Insert, Update, Delete and Search by Linq

 Insert, Update, Delete and Search by Linq with User Store Procedure
Insert, Update, Delete and Search by Linq
There are some steps and code for insert, update, delete and search
by LINQ in SQL SERVER database in ASP.NET:- 
Step 1:- We are using SQL SERVER database. So, we need to create
database and table in SQL SERVER as following code:- 

CREATE DATABASE dbSantoshTest

USE dbSantoshTest

CREATE TABLE tblLinqTest


(
Name varchar(200),Rollno int Primary key,Contactno bigint,Address
nvarchar(max)
)

Step 2:- 

First of all we create an application and give name it LinqTest as shown


in below image:- 
Step 3:- 

Now, Go to Solution Explorer and Right click on LinqTest and go to add


new item and select Webform and give name as Default.aspx page as
shown in below image:-
Step 4:- 

Now, add following code in Default.aspx page:- 

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 128px;
}
#div {
background-color:#0094ff;
color:white;
font-family:Verdana;
font-size:15px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="div">
<center>
<h3>Insert, Update, Delete and Search Operation in SQL Server
By LINQ:-</h3>
<table style="height: 246px">
<tr> <td colspan="2"> <asp:Label ID="lblMessage"
runat="server" Font-Bold="true"></asp:Label> </td></tr>
<tr> <td>Name </td> <td class="auto-style1"><asp:TextBox
ID="txtName" runat="server"></asp:TextBox> </td></tr>
<tr> <td>Roll Number </td> <td class="auto-
style1"><asp:TextBox ID="txtRollno" runat="server"
MaxLength="10"></asp:TextBox> </td></tr>
<tr> <td>Contact Number </td> <td class="auto-
style1"><asp:TextBox ID="txtContactNo" runat="server"
MaxLength="10"></asp:TextBox> </td></tr>
<tr> <td>Address </td> <td class="auto-style1"> <asp:TextBox
ID="txtAddress" runat="server"
TextMode="MultiLine"></asp:TextBox></td></tr>
<tr> <td><asp:Button ID="btnInsert" runat="server"
Text="Insert" Width="150px" Font-Bold="true" Height="30px"
OnClick="btnInsert_Click" /> </td> <td class="auto-
style1"><asp:Button ID="btnUpdate" runat="server" Text="Update"
Width="150px" Font-Bold="true" Height="30px"
OnClick="btnUpdate_Click"/> </td></tr>
<tr> <td><asp:Button ID="btnDelete" runat="server"
Text="Delete" Width="150px" Font-Bold="true" Height="30px"
OnClick="btnDelete_Click" /> </td> <td class="auto-
style1"><asp:Button ID="btnSearch" runat="server" Text="Search"
Width="150px" Font-Bold="true" Height="30px"
OnClick="btnSearch_Click"/> </td></tr>
<tr> <td colspan="2"><asp:Button ID="btnClear" runat="server"
Text="Clear" Width="300px" Height="30px" Font-Bold="true" />
</td></tr>
</table>
<br /> <br />
<asp:GridView ID="gvDetail" runat="server"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px" CellPadding="3" CellSpacing="2">
<FooterStyle BackColor="#F7DFB5"
ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True"
ForeColor="White" />
<PagerStyle ForeColor="#8C4510"
HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-
Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
</center>
</div>
</form>
</body>
</html>

Step 5:- 

Now, Go to Solution Explorer and Right click on LinqTest and go to add


new item and selectLINQ to SQL Classes and give name as
LinqTestDataClasses.dbml as shown in below image:-

Step 6:- 
Now, Go to Server Explorer and drag and drop tblLinqTest table on
LinqTestDataClasses.dbml as shown in below image. 

Now, our application look like this:- 


and connection string in Web.config file is as shown in below:- 

<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application,
please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="dbSantoshTestConnectionString" connectionString="Data
Source=PS-PC\SANTOSH;Initial Catalog=dbSantoshTest;Integrated
Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
</system.web>
</configuration>

Step 7:- 

Now, Go to Default.aspx.cs page and add following code in our


project:- 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Drawing;

public partial class _Default : System.Web.UI.Page


{
//Connection String called from Wec.config
string CS =
ConfigurationManager.ConnectionStrings["dbSantoshTestConnectionString
"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
LoadRecord();
}

//Bind the Gridview code


private void LoadRecord()
{

LinqTestDataClassesDataContext objDC = new


LinqTestDataClassesDataContext();
var query = from data in objDC.GetTable<tblLinqTest>() select
data;
gvDetail.DataSource = query;
gvDetail.DataBind();
}

//Insert method code


public void Insert()
{
try
{
LinqTestDataClassesDataContext objDC = new
LinqTestDataClassesDataContext();
tblLinqTest objtblLinqTest = new tblLinqTest();
objtblLinqTest.Name = txtName.Text;
objtblLinqTest.Rollno = Convert.ToInt32(txtRollno.Text);
objtblLinqTest.Contactno =
Convert.ToInt64(txtContactNo.Text);
objtblLinqTest.Address = txtAddress.Text;
objDC.tblLinqTests.InsertOnSubmit(objtblLinqTest);
objDC.SubmitChanges();
LoadRecord();
Clear();
lblMessage.ForeColor = Color.Black;
lblMessage.Text = "Record Is Inserted!";

}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
LoadRecord();
Clear();
}
}

//Update method code


private void Update()
{
try
{
LinqTestDataClassesDataContext objDC = new
LinqTestDataClassesDataContext();
tblLinqTest objtblLinqTest =
objDC.tblLinqTests.Single(tblLinqTest => tblLinqTest.Rollno ==
Convert.ToInt32(txtRollno.Text));
objtblLinqTest.Contactno =
Convert.ToInt32(txtContactNo.Text);
objtblLinqTest.Name = txtName.Text;
objtblLinqTest.Address = txtAddress.Text;
lblMessage.ForeColor = Color.Black;
lblMessage.Text = "Record is updated!";

LoadRecord();

}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}

//Delete method code


private void Delete()
{
try
{
LinqTestDataClassesDataContext objDC = new
LinqTestDataClassesDataContext();
tblLinqTest objtblLinqTest =
objDC.tblLinqTests.Single(tblLinqTest => tblLinqTest.Rollno ==
Convert.ToInt32(txtRollno.Text));
objDC.tblLinqTests.DeleteOnSubmit(objtblLinqTest);
objDC.SubmitChanges();
lblMessage.ForeColor = Color.Black;
lblMessage.Text = "Record is deleted!";
LoadRecord();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}

//Clear textbox fields code


private void Clear()
{
txtName.Text = "";
txtRollno.Text = "";
txtContactNo.Text = "";
txtAddress.Text = "";
}

protected void btnInsert_Click(object sender, EventArgs e)


{
Insert();
LoadRecord();
Clear();
}

protected void btnUpdate_Click(object sender, EventArgs e)


{
Update();
LoadRecord();
Clear();
}

protected void btnDelete_Click(object sender, EventArgs e)


{
Delete();
LoadRecord();
Clear();
}

protected void btnSearch_Click(object sender, EventArgs e)


{
LoadRecord();
Clear();
}
}

You can , run the application to perform and Insert, Update, Delete
and Search operation
Using LINQ to XML

WHATS RSS FEED


RSS stands for “really simple syndication,” or, depending on who you ask, “rich site
summary.” At their heart they are just simple text files with basic updated information
— news pieces, articles, that sort of thing. 

EXAMPLE WITH LINQ


NEWS.ASPX FILE

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="xmlreader.aspx.cs"


Inherits="xmlreader" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
<asp:Repeater ID="rssRepeater" runat="server">
<ItemTemplate>

<table style="border:solid 1px black;width:500px;font-family:Arial">

<tr>

<td style=" font-weight:bold">

<asp:HyperLink ID="HyperLink1" runat="server"

NavigateUrl = '<%#Eval("link")%>'

Text = '<%#Eval("title")%>'></asp:HyperLink>

</td>

</tr>

<tr>

<td><hr /></td>

</tr>

<tr>

<td style="background-color:#C2D69B">

<asp:Label ID="Label1" runat="server"

Text='<%#Eval("description")%>'></asp:Label>

</td>

</tr>
<tr>

<td> <a href='<%# DataBinder.Eval(Container.DataItem, "id",


"more.aspx?id={0}") %>'>See Details</a>
<hr /></td>

</tr>
</table>

<br />

</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>

CODE BEHIND IS:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class xmlreader : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();

//Read the Response into the DataSet

ds.ReadXml(Server.MapPath("news.xml"));

//Bind the Results to the Repeater

rssRepeater.DataSource = ds.Tables[0];

rssRepeater.DataBind();

}
WHERE XMLFILE IS LIKE THIS :

<?xml version="1.0" encoding="utf-8" ?>


<news>
<singlenew>
<id>1</id>
<link>url1</link>

<title> this first new </title>


<description> dhjjhdjhdgjhdgjhg</description>
<date></date>
</singlenew>
<singlenew>
<id>2</id>
<link>url1</link>

<title> this first new </title>


<description> dhjjhdjhdgjhdgjhg</description>
<date></date>
</singlenew>

</news>

}Creating Sample XML using LINQ

In LINQ to XML we have XElement and XAttribute object


constructors to create XML Document. XElement will be used
to create Element and XAttribute will be used to add
attribute(s) to the element.

Reading XML using LINQ


By using XDocument object we can load XML documents, Writing linq
queries on XDocument will return collection. In linq query
xdocument.Descendants will return a IEnumarable XElement collection.

Lets take an example XML file which conatins country and city list.
Take two dropdown lists, the first one has to be filled with counties list by
reading xml. And when user select country from the dropdown, get the cities
list in that country from the xml and bind it to second dropdown.

USA

Example :   Country :            City :      

Input XML :

<?xml version="1.0" encoding="utf-8" ?>
<countries>
  <country name='India'>
    <city>Delhi</city>
    <city>Mumbai</city>
    <city>Hyderabad</city>
  </country>
  <country name='Australia'>
    <city>Sydney</city>
    <city>Hobart</city>
    <city>Canberra</city>
  </country>
  <country name='Canada'>
    <city>Toronto</city>
    <city>Niagara</city>
    <city>Victoria</city>
  </country>
  <country name='USA'>
    <city>Dallas</city>
    <city>Washington</city>
    <city>Chicago</city>
  </country>
</countries>

LINQ Code :

In PageLoad :

XDocument xdoc = XDocument.Load("D:\\countries.xml");
var countires
= from country in xdoc.Descendants("countries").Elements("coun
try").Attributes("name")
                select country.Value;
ddlCountry.DataSource = countires;
ddlCountry.DataBind();
 
var cities
= from country in xdoc.Descendants("countries").Elements("coun
try")
                where country.Attribute("name").Value ==
ddlCountry.SelectedValue
                from city in country.Elements("city")
                orderby city.Value
                select city.Value;
 
ddlCity.DataSource = cities;
ddlCity.DataBind();
 

In ddlCountry SelectedIndexChanged :

protected void ddlCountry_SelectedIndexChanged(object sender, 
EventArgs e)
{
    try
    {
        XDocument xdoc = XDocument.Load("D:\\countries.xml");
        var cities
= from country in xdoc.Descendants("countries").Elements("coun
try")
                        where country.Attribute("name").Value
== ddlCountry.SelectedValue
                        from city in country.Elements("city")
                        orderby city.Value
                        select city.Value;
 
        ListBox1.DataSource = cities;
        ListBox1.DataBind();
    }
    catch
    {
    }
}

Reading XML using LINQ


By using XDocument.Parse() method we can convert/read xml string to XDocumnet in LINQ. and we can set the xml
to gridview as a result set. i.e. we can select the required columns and can assign it to a gridview.

Example :

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

Code Behind (C#) :


XDocument xdoc = 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()
            select new
            {
                EmployeeName = emp.Element("Name").Value,
                Department = emp.Element("Department").Value,
                Salary = emp.Element("Salary").Value
            };
gvXML.DataSource = res;
gvXML.DataBind();
 

Output :
EmployeeNam
Department Salary
e
Thomas Accounts 5000
Wills Accounts 24000
Brod Finance 28000
Smith Finance 21000

LINQ to XML Where condition to filter records

In this example we will check how to apply where condition to filter records in XML by using LINQ.

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 emp.Element("Department").Value == "Accounts"
            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 :
EmployeeNam Designatio
Department Salary
e n
Thomas Executive Accounts 5000
Wills Manager Accounts 24000

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 ha
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 :
EmployeeNam Designatio
Department Salary
e n
Smith Analyst Finance 21000
Wills Manager Accounts 24000
Previous

Linq - XML search using Contains 

I use the Linq technology to read an XML file, but I have a problem when
I try to search something in it.

I would like to know how can I use something such as the "like operator".
 var parameters = from param in xferDoc.Descendants("parameter") 
             where param.Attributes("code").Contains(searchString) 
             orderby (string)param.Element("description") 
             select new { 
                     code = param.Attribute("code").Value, 
                     description = param.Element("description").Value, 
                     unit = param.Element("unit").Value 
                       }; 

Assuming the example XML looks like this:


Code Snippet
<?xml version="1.0" encoding="utf-8" ?>
<test>
  <parameters>
    <parameter code="ABC">
      <description>Automation</description>
      <unit>s</unit>
    </parameter>
    <parameter code="EFG">
      <description>Engineering</description>
      <unit>eng</unit>
    </parameter>
    <parameter code="MNO">
      <description>Machine</description>
      <unit>mac</unit>
    </parameter>
  </parameters>
</test>

Then the following query

Code Snippet
            string exampleCode = "BC";
            string exampleDescription = "ring";
            XElement test = XElement.Load(@"..\..\XMLFile1.xml");
            var query = from param in test.Descendants("parameter")
                        where
((string)param.Attribute("code")).Contains(exampleCode)
                        ||
((string)param.Element("description")).Contains(exampleDescription
)
                        select new
                        {
                            code = (string)param.Attribute("code"),
                            desc = (string)param.Element("description"),
                            unit = (string)param.Element("unit")
                        };
            foreach (var item in query)
            {
                Response.WriteLine("code: {0}; description: {1}; unit:
{2}", item.code, item.desc, item.unit);
            }

It is not clear how the XML looks you want to search.


And it is not clear to me whether you simply want to use the string
method Contains to search an attribute's string value or whether you
want to use the LINQ Contains method.

Here is an example using the string method Contains on an attribute's


value:

Code Snippet
XElement root = XElement.Parse(@"<root>
<foo val=""foobar"">1</foo>

<foo val=""baz"">2</foo>

<foo val=""bar"">3</foo>

</root>");
var query = from foo in root.Elements("foo")
where foo.Attribute("val").Value.Contains("bar")
select (int)foo;
foreach (var i in query)
{

response.WriteLe(i);
}

That sample outputs

1
3

Code Snippet
<?xml version="1.0" encoding="ISO-8859-1" ?> 
- <test>
- <parameters>
- <parameter code="ABC">
  <description>Automation</description> 
  <unit>s</unit> 
  </parameter>
- <parameter code="EFG">
  <description>Engineering</description> 
  <unit>eng</unit> 
  </parameter>
- <parameter code="MNO">
  <description>Machine</description> 
  <unit>mac</unit>   </parameter>
...

There is above an example of my XML file... If I also try to search


something in description field, how do I have to code?

Your first post seemed to search based on the code attribute, now you
say "also try to search something in the description field", so it is not
clear what you want to achieve.
Your XML sample gives us an idea of the XML you want to search,
can you also tell us which value you want to look for? For instance
you have description values like "Automation" or "Engineering", do
you get one of those and want to find the parameter elements
containing such a description? Or do you get only fragments like e.g.
"Auto" and want to find the parameter elements having a description
like "Automation"?

Assuming the example XML looks like this:

Code Snippet
<?xml version="1.0" encoding="utf-8" ?>
<test>
  <parameters>
    <parameter code="ABC">
      <description>Automation</description>
      <unit>s</unit>
    </parameter>
    <parameter code="EFG">
      <description>Engineering</description>
      <unit>eng</unit>
    </parameter>
    <parameter code="MNO">
      <description>Machine</description>
      <unit>mac</unit>
    </parameter>
  </parameters>
</test>

Then the following query

Code Snippet
            string exampleCode = "BC";
            string exampleDescription = "ring";
            XElement test = XElement.Load(@"..\..\XMLFile1.xml");
            var query = from param in test.Descendants("parameter")
                        where
((string)param.Attribute("code")).Contains(exampleCode)
                        ||
((string)param.Element("description")).Contains(exampleDescription
)
                        select new
                        {
                            code = (string)param.Attribute("code"),
                            desc = (string)param.Element("description"),
                            unit = (string)param.Element("unit")
                        };
            foreach (var item in query)
            {
                response.WriteLine("code: {0}; description: {1}; unit:
{2}", item.code, item.desc, item.unit);
            }

 
1. example to Read XML file using LINQ to XML

There are two ways to do so: Using the XElement class or the XDocument class.
Both the classes contain the ‘Load()’ method which accepts a file, a URL or
XMLReader and allows XML to be loaded. The primary difference between both
the classes is that an XDocument can contain XML declaration, XML Document
Type (DTD) and processing instructions. Moreover an XDocument contains one
root XElement.

Using XElement

C#

XElement xelement = XElement.Load("..\\..\\Employees.xml");


IEnumerable<XElement> employees = xelement.Elements();
// Read the entire XML
foreach (var employee in employees)
{
    Response.WriteLine(employee);
}

Output:

Using XDocument

C#

XDocument xdocument = XDocument.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xdocument.Elements();
foreach (var employee in employees)
{
    Response.WriteLine(employee);
}
 

Output:
Note 1: As you can observe, XDocument contains a single root element
(Employees).

Note 2: In order to generate an output similar to the one using XElement, use
“xdocument.Root.Elements()” instead of  “xdocument.Elements()”

Note 3: VB.NET users can use a new feature called XML Literal.

2. How Do I Access a Single Element using LINQ to XML

Let us see how to access the name of all the Employees and list them over here

C#

XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
Response.WriteLine("List of all Employee Names :");
foreach (var employee in employees)
{
    Response.WriteLine(employee.Element("Name").Value);
}
 

Output:

3. How Do I Access Multiple Elements using LINQ to XML

Let us see how to access the name of all Employees and also list the ID along
with it

C#

XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
Response.WriteLine("List of all Employee Names along with their
ID:");
foreach (var employee in employees)
{
    Response.WriteLine("{0} has Employee ID {1}",
        employee.Element("Name").Value,
        employee.Element("EmpId").Value);
}

Output:

4. How Do I Access all Elements having a Specific Attribute using LINQ to


XML

Let us see how to access details of all Female Employees

C#

XElement xelement = XElement.Load("..\\..\\Employees.xml");
var name = from nm in xelement.Elements("Employee")
           where (string)nm.Element("Sex") == "Female"
           select nm;
Response.WriteLine("Details of Female Employees:");
foreach (XElement xEle in name)
    Response.WriteLine(xEle);
 

Output:

5. How Do I access Specific Element having a Specific Attribute using


LINQ to XML

Let us see how to list all the Home Phone Nos.

C#

XElement xelement = XElement.Load("..\\..\\Employees.xml");
var homePhone = from phoneno in xelement.Elements("Employee")
                where (string)phoneno.Element("Phone").Attribute("Typ
e") == "Home"
                select phoneno;
Response.WriteLine("List HomePhone Nos.");
foreach (XElement xEle in homePhone)
{
    Response.WriteLine(xEle.Element("Phone").Value);
}
 

Output:

6. How Do I Find an Element within another Element using LINQ to XML

Let us see how to find the details of Employees living in 'Alta' City

C#

XElement xelement = XElement.Load("..\\..\\Employees.xml");
var addresses = from address in xelement.Elements("Employee")
                where (string)address.Element("Address").Element("Cit
y") == "Alta"
               select address;
Response.WriteLine("Details of Employees living in Alta City");
foreach (XElement xEle in addresses)
    Response.WriteLine(xEle);
 

Output:

7. How Do I Find Nested Elements (using Descendants Axis) using LINQ


to XML

Let us see how to list all the zip codes in the XML file

C#

XElement xelement = XElement.Load("..\\..\\Employees.xml");
Response.WriteLine("List of all Zip Codes");
foreach (XElement xEle in xelement.Descendants("Zip"))
{
    Response.WriteLine((string)xEle);
}
 

Output:
8. How do I apply Sorting on Elements using LINQ to XML

Let us see how to List and Sort all Zip Codes in ascending order

C#

XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<string> codes
= from code in xelement.Elements("Employee")
                            let zip =
(string)code.Element("Address").Element("Zip")
                            orderby zip
                            select zip;
Response.WriteLine("List and Sort all Zip Codes");
 
foreach (string zp in codes)
    Response.WriteLine(zp);
 

Output:

Section 2: Manipulate XML content and Persist the changes using


LINQ To XML
 

9. Create an XML Document with Xml Declaration/Namespace/Comments


using LINQ to XML

When you need to create an XML document containing XML declaration, XML
Document Type (DTD) and processing instructions, Comments, Namespaces, you
should go in for the XDocument class.

C#

XNamespace empNM = "urn:lst-emp:emp";
 
XDocument xDoc = new XDocument(
            new XDeclaration("1.0", "UTF-16", null),
            new XElement(empNM + "Employees",
                new XElement("Employee",
                    new XComment("Only 3 elements for demo
purposes"),
                    new XElement("EmpId", "5"),
                    new XElement("Name", "Kimmy"),
                    new XElement("Sex", "Female")
                    )));
 
StringWriter sw = new StringWriter();
xDoc.Save(sw);

10. Save the XML Document to a XMLWriter or to the disk using LINQ to


XML

Use the following code to save the XML to a XMLWriter or to your physical disk

C#

XNamespace empNM = "urn:lst-emp:emp";
 
XDocument xDoc = new XDocument(
            new XDeclaration("1.0", "UTF-16", null),
            new XElement(empNM + "Employees",
                new XElement("Employee",
                    new XComment("Only 3 elements for demo
purposes"),
                    new XElement("EmpId", "5"),
                    new XElement("Name", "Kimmy"),
                    new XElement("Sex", "Female")
                    )));
 
StringWriter sw = new StringWriter();
XmlWriter xWrite = XmlWriter.Create(sw);
xDoc.Save(xWrite);
xWrite.Close();
 
// Save to Disk
xDoc.Save("C:\\Something.xml");
Response.WriteLine("Saved");

 
11. Load an XML Document using XML Reader using LINQ to XML

Use the following code to load the XML Document into an XML Reader

C#

XmlReader xRead = XmlReader.Create(@"..\\..\\Employees.xml");
XElement xEle = XElement.Load(xRead);
Response.WriteLine(xEle);
xRead.Close();
 

12. Find Element at a Specific Position using LINQ to XML

Find the 2nd Employee Element

C#

// Using XElement
Response.WriteLine("Using XElement");
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emp1 = xEle.Descendants("Employee").ElementAt(1);
Response.WriteLine(emp);
 
Response.WriteLine("------------");
 
//// Using XDocument
Response.WriteLine("Using XDocument");
XDocument xDoc = XDocument.Load("..\\..\\Employees.xml");
var emp1 = xDoc.Descendants("Employee").ElementAt(1);
Response.WriteLine(emp);

13. List the First 2 Elements using LINQ to XML


List the details of the first 2 Employees

C#

XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Take(2);
foreach (var emp in emps)
    Response.WriteLine(emp);

14. List the 2nd and 3rd Element using LINQ to XML

List the 2nd and 3rd Employees

C#

XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Skip(1).Take(2);
foreach (var emp in emps)
    Response.WriteLine(emp);

15. List the Last 2 Elements using LINQ To XML


We have been posting the entire elements as output in our previous examples.
Let us say that you want to display only the Employee Name, use this query:

C#

XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Reverse().Take(2);
foreach (var emp in emps)
    Response.WriteLine(emp.Element("EmpId") + "" +
emp.Element("Name"));

To display only the values without the XML tags, use the ‘Value’ property

C#

XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Reverse().Take(2);
foreach (var emp in emps)
    Response.WriteLine(emp.Element("EmpId").Value + ". " +
emp.Element("Name").Value);
 

If you notice, the results are not ordered i.e. the Employee 4 is printed before 3.
To order the results, just add call Reverse() again while filtering as shown below:

C#

XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps =
xEle.Descendants("Employee").Reverse().Take(2).Reverse();
foreach (var emp in emps)
    Response.WriteLine(emp.Element("EmpId").Value + ". " +
emp.Element("Name").Value);

16. Find the Element Count based on a condition using LINQ to XML

Count the number of Employees living in the state CA

C#

XElement xelement = XElement.Load("..\\..\\Employees.xml");
var stCnt = from address in xelement.Elements("Employee")
            where (string)address.Element("Address").Element("State")
== "CA"
            select address;
Response.WriteLine("No of Employees living in CA State are {0}",
stCnt.Count());
17. Add a new Element at runtime using LINQ to XML

You can add a new Element to an XML document at runtime by using the Add()
method of XElement. The new Element gets added as the last element of the XML
document.

C#

 XElement xEle = XElement.Load("..\\..\\Employees.xml");
 xEle.Add(new XElement("Employee",
     new XElement("EmpId", 5),
     new XElement("Name", "George")));
 
 Response.Write(xEle);

18. Add a new Element as the First Child using LINQ to XML

In the previous example, by default the new Element gets added to the end of
the XML document. If you want to add the Element as the First Child, use the
‘AddFirst()’ method

C#

XElement xEle = XElement.Load("..\\..\\Employees.xml");
    xEle.AddFirst(new XElement("Employee",
        new XElement("EmpId", 5),
        new XElement("Name", "George")));
 
    Response.Write(xEle);

19. Add an attribute to an Element using LINQ to XML

To add an attribute to an Element, use the following code:

C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
    xEle.Add(new XElement("Employee",
        new XElement("EmpId", 5),
        new XElement("Phone", "423-555-4224", new XAttribute("Type", 
"Home"))));
 
    Response.Write(xEle);

20. Replace Contents of an Element/Elements using LINQ to XML

Let us say that in the XML file, you want to change the Country from “USA” to
“United States of America” for all the Elements. Here’s how to do so:

C#

XElement xEle = XElement.Load("..\\..\\Employees.xml");
    var countries =
xEle.Elements("Employee").Elements("Address").Elements("Country").ToL
ist();
    foreach (XElement cEle in countries)
        cEle.ReplaceNodes("United States Of America");
 
    Response.Write(xEle);
21. Remove an attribute from all the Elements using LINQ to XML

Let us say if you want to remove the Type attribute ( <Phone Type=”Home”>)
attribute for all the elements, then here’s how to do it.

C#

XElement xEle = XElement.Load("..\\..\\Employees.xml");
    var phone = xEle.Elements("Employee").Elements("Phone").ToList();
    foreach (XElement pEle in phone)
        pEle.RemoveAttributes();
 
    Response.Write(xEle);

To remove attribute of one Element based on a condition, traverse to that


Element and SetAttributeValue("Type", null); You can also use
SetAttributeValue(XName,object) to update an attribute value.

22. Delete an Element based on a condition using LINQ to XML

If you want to delete an entire element based on a condition, here’s how to do it.
We are deleting the entire Address Element

C#

XElement xEle = XElement.Load("..\\..\\Employees.xml");
    var addr = xEle.Elements("Employee").ToList();
    foreach (XElement addEle in addr)
        addEle.SetElementValue("Address", null);
 
    Response.Write(xEle);

 
SetElementValue() can also be used to Update the content of an Element.

23. Remove ‘n’ number of Elements using LINQ to XML

If you have a requirement where you have to remove ‘n’ number of Elements; For
E.g. To remove the last 2 Elements, then here’s how to do it

C#

XElement xEle = XElement.Load("..\\..\\Employees.xml");
    var emps = xEle.Descendants("Employee");
    emps.Reverse().Take(2).Remove();
 
    Response.Write(xEle);

      

24. Save/Persists Changes to the XML using LINQ to XML

All the manipulations we have done so far were in the memory and were not
persisted in the XML file. If you have been wondering how to persist changes to
the XML, once it is modified, then here’s how to do so. It’s quite simple. You just
need to call the Save() method. It’s also worth observing that the structure of the
code shown below is similar to the structure of the end result (XML document).
That’s one of the benefits of LINQ to XML, that it makes life easier for developers
by making it so easy to create and structure XML documents.

C#

    XElement xEle = XElement.Load("..\\..\\Employees.xml");
    xEle.Add(new XElement("Employee",
    new XElement("EmpId", 5),
    new XElement("Name", "George"),
    new XElement("Sex", "Male"),
    new XElement("Phone", "423-555-4224", new XAttribute("Type", "Hom
e")),
    new XElement("Phone", "424-555-0545", new XAttribute("Type", "Wor
k")),
    new XElement("Address",
        new XElement("Street", "Fred Park, East Bay"),
        new XElement("City", "Acampo"),
        new XElement("State", "CA"),
        new XElement("Zip", "95220"),
        new XElement("Country", "USA"))));
 
    xEle.Save("..\\..\\Employees.xml");
    Response.WriteLe(xEle);
 
            

You might also like