Linq 2019 PDF
Linq 2019 PDF
The acronym LINQ stands for Language Integrated Query. Microsoft’s query
language is fully integrated and offers easy data access from in-memory objects
//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);
Example 1
var colours = new string[] { "Red", "Orange", "Yellow", "Green", "Blue", "Indigo",
"Violet" };
foreach(string s in longNames)
{
Response.WriteLe(s);
}
/* OUTPUT in browser
Orange
Yellow
Green
Indigo
Violet
*/
Another example
Red
IEnumerable<int> topThreeGrades =
grades.OrderByDescending(grade => grade).Take(3);
result: /*
TakeWhile operator
string[] fruits = { "apple", "banana", "mango", "orange",
"passionfruit", "grape" };
IEnumerable<string> query =
fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);
/*
ا هعناها اطبع الفواكه الى اى تصل كلوه
orange
This code produces the following output:
apple
banana
mango
*/
Example 2
The following example creates a sequence with large number of int values:
output
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(' ');
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,
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>
USE dbSantoshTest
Step 2:-
<!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:-
Step 6:-
Now, Go to Server Explorer and drag and drop tblLinqTest table on
LinqTestDataClasses.dbml as shown in below image.
<?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:-
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;
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
LoadRecord();
Clear();
}
}
LoadRecord();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
You can , run the application to perform and Insert, Update, Delete
and Search operation
Using LINQ to XML
<!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>
<tr>
NavigateUrl = '<%#Eval("link")%>'
Text = '<%#Eval("title")%>'></asp:HyperLink>
</td>
</tr>
<tr>
<td><hr /></td>
</tr>
<tr>
<td style="background-color:#C2D69B">
Text='<%#Eval("description")%>'></asp:Label>
</td>
</tr>
<tr>
</tr>
</table>
<br />
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
ds.ReadXml(Server.MapPath("news.xml"));
rssRepeater.DataSource = ds.Tables[0];
rssRepeater.DataBind();
}
WHERE XMLFILE IS LIKE THIS :
</news>
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 :
LINQ Code :
In PageLoad :
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 :
ListBox1.DataSource = cities;
ListBox1.DataBind();
}
catch
{
}
}
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>
Output :
EmployeeName Department Salary
Thomas Accounts 5000
Wills Accounts 24000
Brod Finance 28000
Smith Finance 21000
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>
Output :
EmployeeName Designation Department Salary
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>
Output :
EmployeeName Designation Department Salary
Smith Analyst Finance 21000
Wills Manager Accounts 24000
Previous
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
};
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);
}
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>
...
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"?
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>
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#
Output:
Using XDocument
C#
Output:
Note 3: VB.NET users can use a new feature called XML Literal.
Let us see how to access the name of all the Employees and list them over here
C#
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#
Output:
C#
Output:
5. How Do I access Specific Element having a Specific Attribute using
LINQ to XML
C#
Output:
Let us see how to find the details of Employees living in 'Alta' City
C#
Output:
C#
Output:
Let us see how to List and Sort all Zip Codes in ascending order
C#
Output:
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";
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#
// 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();
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("------------");
C#
14. List the 2nd and 3rd Element using LINQ to XML
C#
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#
To display only the values without the XML tags, use the „Value‟ property
C#
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#
16. Find the Element Count based on a condition using LINQ to XML
C#
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#
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#
C#
Response.Write(xEle);
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#
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#
Response.Write(xEle);
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#
Response.Write(xEle);
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#
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#
xEle.Save("..\\..\\Employees.xml");
Response.WriteLe(xEle);