Linq to XML using C# and VB.Net

A lot of developers over the past few months have requested us for tutorials focusing on LINQToXML. Although I have written a couple of them in the past, I decided to republish these tips in the form of a single post. In this article, we will explore 24 ‘How Do I’ kind of examples using LINQ to XML. I assume you are familiar with LINQ. If not, you can start off with LINQ by checking some tutorials over here and here.
 Excel file API for: XLS, XLSX, CSV and ODS
For this article, we will be using a sample file called ‘Employees.xml’ for all our samples which is available with the source code. So make sure you keep it handy with you while are practicing these examples. The mark up for Employees.xml is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
 <Employee>
    <EmpId>1</EmpId>
    <Name>Sam</Name>   
    <Sex>Male</Sex>
    <Phone Type="Home">423-555-0124</Phone>
    <Phone Type="Work">424-555-0545</Phone>
   <Address>
      <Street>7A Cox Street</Street>
      <City>Acampo</City>
      <State>CA</State>
      <Zip>95220</Zip>
      <Country>USA</Country>
    </Address>
 </Employee>
 <Employee>
    <EmpId>2</EmpId>
    <Name>Lucy</Name>
    <Sex>Female</Sex>
    <Phone Type="Home">143-555-0763</Phone>
    <Phone Type="Work">434-555-0567</Phone>
    <Address>
      <Street>Jess Bay</Street>
      <City>Alta</City>
      <State>CA</State>
      <Zip>95701</Zip>
      <Country>USA</Country>
    </Address>
 </Employee>
 <Employee>
    <EmpId>3</EmpId>
    <Name>Kate</Name>
    <Sex>Female</Sex>
    <Phone Type="Home">166-555-0231</Phone>
    <Phone Type="Work">233-555-0442</Phone>
    <Address>
      <Street>23 Boxen Street</Street>
      <City>Milford</City>
      <State>CA</State>
      <Zip>96121</Zip>
      <Country>USA</Country>
    </Address>
 </Employee>
 <Employee>
    <EmpId>4</EmpId>
    <Name>Chris</Name>
    <Sex>Male</Sex>
    <Phone Type="Home">564-555-0122</Phone>
    <Phone Type="Work">442-555-0154</Phone>
    <Address>
      <Street>124 Kutbay</Street>
      <City>Montara</City>
      <State>CA</State>
      <Zip>94037</Zip>
      <Country>USA</Country>
    </Address>
 </Employee>
</Employees>
 
The application is a console application targeting .NET 3.5 framework, although you can use the latest .NET 4.0 framework too. I have also used ‘query expressions’, instead of Lambda expression in these samples. It is just a matter of preference and you are free to use any of these.
This tutorial has been divided into 2 sections:
Section 1: Read XML and Traverse the Document using LINQ To XML
Section 2: Manipulate XML content and Persist the changes using LINQ To XML
The following namespaces are needed while testing the samples: System; System.Collections.Generic; System.Linq; System.Text; System.Xml; System.Xml.Linq;
Go grab a hot cup of coffee, put on your developer cap and let us get started:
 
Section 1: Read XML and Traverse the XML Document using LINQ To XML
 
1. How Do I Read XML 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)
{
    Console.WriteLine(employee);
}
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim employees As IEnumerable(Of XElement) = xelement.Elements()
' Read the entire XML
For Each employee In employees
      Console.WriteLine(employee)
Next employee
Output:
image_1
Using XDocument
C#
XDocument xdocument = XDocument.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xdocument.Elements();
foreach (var employee in employees)
{
    Console.WriteLine(employee);
}
 
VB.NET (Converted Code)
Dim xdocument As XDocument = XDocument.Load("..\..\Employees.xml")
Dim employees As IEnumerable(Of XElement) = xdocument.Elements()
For Each employee In employees
      Console.WriteLine(employee)
Next employee
Output:
image_11
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();
Console.WriteLine("List of all Employee Names :");
foreach (var employee in employees)
{
    Console.WriteLine(employee.Element("Name").Value);
}
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim employees As IEnumerable(Of XElement) = xelement.Elements()
Console.WriteLine("List of all Employee Names :")
For Each employee In employees
      Console.WriteLine(employee.Element("Name").Value)
Next employee
Output:
image_2
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();
Console.WriteLine("List of all Employee Names along with their ID:");
foreach (var employee in employees)
{
    Console.WriteLine("{0} has Employee ID {1}",
        employee.Element("Name").Value,
        employee.Element("EmpId").Value);
}
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim employees As IEnumerable(Of XElement) = xelement.Elements()
Console.WriteLine("List of all Employee Names along with their ID:")
For Each employee In employees
      Console.WriteLine("{0} has Employee ID {1}", employee.Element("Name").Value, employee.Element("EmpId").Value)
Next employee
Output:
image_3
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;
Console.WriteLine("Details of Female Employees:");
foreach (XElement xEle in name)
    Console.WriteLine(xEle);
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim name = _
      From nm In xelement.Elements("Employee") _
      Where CStr(nm.Element("Sex")) = "Female" _
      Select nm
Console.WriteLine("Details of Female Employees:")
For Each xEle As XElement In name
      Console.WriteLine(xEle)
Next xEle
Output:
image_4
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("Type") == "Home"
                select phoneno;
Console.WriteLine("List HomePhone Nos.");
foreach (XElement xEle in homePhone)
{
    Console.WriteLine(xEle.Element("Phone").Value);
}
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim homePhone = _
      From phoneno In xelement.Elements("Employee") _
      Where CStr(phoneno.Element("Phone").Attribute("Type")) = "Home" _
      Select phoneno
Console.WriteLine("List HomePhone Nos.")
For Each xEle As XElement In homePhone
      Console.WriteLine(xEle.Element("Phone").Value)
Next xEle
Output:
image_5
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("City") == "Alta"
               select address;
Console.WriteLine("Details of Employees living in Alta City");
foreach (XElement xEle in addresses)
    Console.WriteLine(xEle);
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim addresses = _
      From address In xelement.Elements("Employee") _
      Where CStr(address.Element("Address").Element("City")) = "Alta" _
      Select address
Console.WriteLine("Details of Employees living in Alta City")
For Each xEle As XElement In addresses
      Console.WriteLine(xEle)
Next xEle
Output:
image_26
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");
Console.WriteLine("List of all Zip Codes");
foreach (XElement xEle in xelement.Descendants("Zip"))
{
    Console.WriteLine((string)xEle);
}
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Console.WriteLine("List of all Zip Codes")
For Each xEle As XElement In xelement.Descendants("Zip")
      Console.WriteLine(CStr(xEle))
Next xEle
Output:
image_37
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;
Console.WriteLine("List and Sort all Zip Codes");
 
foreach (string zp in codes)
    Console.WriteLine(zp);
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim codes As IEnumerable(Of String) = _
      From code In xelement.Elements("Employee") _
      Let zip = CStr(code.Element("Address").Element("Zip")) _
      Order By zip _
      Select zip
Console.WriteLine("List and Sort all Zip Codes")
 
For Each zp As String In codes
      Console.WriteLine(zp)
Next zp
Output:
image_48
 
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);
Console.WriteLine(sw);
VB.NET (Converted Code)
        Dim empNM As XNamespace = "urn:lst-emp:emp"
 
        Dim xDoc As New XDocument(New XDeclaration("1.0", "UTF-16", Nothing), _
                    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"))))
 
        Dim sw As New StringWriter()
        xDoc.Save(sw)
        Console.WriteLine(sw)
image_59
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");
Console.WriteLine("Saved");
VB.NET (Converted Code)
       Dim empNM As XNamespace = "urn:lst-emp:emp"
 
Dim xDoc As New XDocument(New XDeclaration("1.0", "UTF-16", Nothing),_
        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"))))
 
        Dim sw As New StringWriter()
        Dim xWrite As XmlWriter = XmlWriter.Create(sw)
        xDoc.Save(xWrite)
        xWrite.Close()
 
        ' Save to Disk
        xDoc.Save("C:\Something.xml")
        Console.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);
Console.WriteLine(xEle);
xRead.Close();
VB.NET (Converted Code)
Dim xRead As XmlReader = XmlReader.Create("..\\..\\Employees.xml")
Dim xEle As XElement = XElement.Load(xRead)
Console.WriteLine(xEle)
xRead.Close()
image_110
 
12. Find Element at a Specific Position using LINQ to XML
Find the 2nd Employee Element
C#
// Using XElement
Console.WriteLine("Using XElement");
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emp1 = xEle.Descendants("Employee").ElementAt(1);
Console.WriteLine(emp);
 
Console.WriteLine("------------");
 
//// Using XDocument
Console.WriteLine("Using XDocument");
XDocument xDoc = XDocument.Load("..\\..\\Employees.xml");
var emp1 = xDoc.Descendants("Employee").ElementAt(1);
Console.WriteLine(emp);
VB.NET (Converted Code)
' Using XElement
Console.WriteLine("Using XElement")
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emp1 = xEle.Descendants("Employee").ElementAt(1)
Console.WriteLine(emp)
 
Console.WriteLine("------------")
 
'// Using XDocument
Console.WriteLine("Using XDocument")
Dim xDoc As XDocument = XDocument.Load("..\..\Employees.xml")
Dim emp1 = xDoc.Descendants("Employee").ElementAt(1)
Console.WriteLine(emp)
image_211
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)
    Console.WriteLine(emp);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emps = xEle.Descendants("Employee").Take(2)
For Each emp In emps
      Console.WriteLine(emp)
Next emp
image_312
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)
    Console.WriteLine(emp);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emps = xEle.Descendants("Employee").Skip(1).Take(2)
For Each emp In emps
      Console.WriteLine(emp)
Next emp
image_413
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)
    Console.WriteLine(emp.Element("EmpId") + "" + emp.Element("Name"));
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emps = xEle.Descendants("Employee").Reverse().Take(2)
For Each emp In emps
      Console.WriteLine(emp.Element("EmpId") + emp.Element("Name"))
Next emp
image_514
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)
    Console.WriteLine(emp.Element("EmpId").Value + ". " + emp.Element("Name").Value);
 
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emps = xEle.Descendants("Employee").Reverse().Take(2)
For Each emp In emps
      Console.WriteLine(emp.Element("EmpId").Value & ". " & emp.Element("Name").Value)
Next emp
image_115
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)
    Console.WriteLine(emp.Element("EmpId").Value + ". " + emp.Element("Name").Value);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emps = xEle.Descendants("Employee").Reverse().Take(2).Reverse()
For Each emp In emps
      Console.WriteLine(emp.Element("EmpId").Value & ". " & emp.Element("Name").Value)
Next emp
image_216
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;
Console.WriteLine("No of Employees living in CA State are {0}", stCnt.Count());
VB.NET (Converted Code)
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var stCnt = from address in xelement.Elements("Employee")
            where (string)address.Element("Address").Element("State") == "CA"
            select address;
Console.WriteLine("No of Employees living in CA State are {0}", stCnt.Count());
image_317
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")));
 
 Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        xEle.Add(New XElement("Employee", _
                              New XElement("EmpId", 5), _
                              New XElement("Name", "George")))
 
Console.Write(xEle)
image_418
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")));
 
    Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
   xEle.AddFirst(New XElement("Employee", _
      New XElement("EmpId", 5), _
      New XElement("Name", "George")))
 
Console.Write(xEle)
 
image_518
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"))));
 
    Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        xEle.Add(New XElement("Employee", _
                              New XElement("EmpId", 5), _
                              New XElement("Phone", "423-555-4224", _
                                           New XAttribute("Type", "Home"))))
 
        Console.Write(xEle)
image_119
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").ToList();
    foreach (XElement cEle in countries)
        cEle.ReplaceNodes("United States Of America");
 
    Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        Dim countries = xEle.Elements("Employee").Elements("Address").Elements("Country").ToList()
        For Each cEle As XElement In countries
            cEle.ReplaceNodes("United States Of America")
        Next cEle
 
Console.Write(xEle)
 
image_220
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();
 
    Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        Dim phone = xEle.Elements("Employee").Elements("Phone").ToList()
        For Each pEle As XElement In phone
            pEle.RemoveAttributes()
        Next pEle
 
Console.Write(xEle)
image_321
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);
 
    Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
    Dim addr = xEle.Elements("Employee").ToList()
        For Each addEle As XElement In addr
            addEle.SetElementValue("Address", Nothing)
        Next addEle
 
Console.Write(xEle)
 
image_422
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();
 
    Console.Write(xEle);
VB.NET (Converted Code)
       Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        Dim emps = xEle.Descendants("Employee")
        emps.Reverse().Take(2).Remove()
 
        Console.Write(xEle)
image_523
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", "Home")),
    new XElement("Phone", "424-555-0545", new XAttribute("Type", "Work")),
    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");
    Console.WriteLine(xEle);
 
    Console.ReadLine();           
VB.NET (Converted Code)
Dim xEle As XElement = 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", "Home")), _
                 New XElement("Phone", "424-555-0545", _
                   New XAttribute("Type", "Work")), _
                   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")
        Console.WriteLine(xEle)
 
        Console.ReadLine()

LINQ in C#.Net

What is LINQ?
Microsoft Babies
Microsoft new baby yes I am talking about LINQ stand for Language-Integrated Query is now available as a integral part of Visual Studio Orcas. Microsoft releases the new Visual Studio with the name of Orcas and all Microsoft previous efforts (Windows Communication Foundation WCF, Windows Workflow Foundation WWF, Windows Presentation Foundation WPF, Windows CardSpace and LINQ) are integrated in this Studio. From last one and half years Anders Hejlsberg team done a tremendous job in the overcoming the gap between the data impedance. Mr. Anders team gives a native syntax to developers in the form LINQ to C# and VB.Net for accessing data from any repository. The repository could be in memory object, database (still MS SQL Server only) and XML files.
 
What is LINQ?
Still lots of folks don’t understand what LINQ is doing. Basically LINQ address the current database development model in the context of Object Oriented Programming Model. If some one wants to develop database application on .Net platform the very simple approach he uses ADO.Net. ADO.Net is serving as middle ware in application and provides complete object oriented wrapper around the database SQL. Developing application in C# and VB.Net so developer must have good knowledge of object oriented concept as well as SQL, so it means developer must be familiar with both technologies to develop an application. If here I can say SQL statements are become part of the C# and VB.Net code so it’s not mistaken in form of LINQ. According to Anders Hejlsberg the chief architect of C#.
 
             “Microsoft original motivation behind LINQ was to address the impedance mismatch between programming languages and database.”
 
LINQ has a great power of querying on any source of data, data source could be the collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface. Microsoft basically divides LINQ into three areas and that are give below.
 
  • LINQ to Object {Queries performed against the in-memory data}
  • LINQ to ADO.Net
    • LINQ to SQL (formerly DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported}
    • LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables}
    • LINQ to Entities {Microsoft ORM solution}
  • LINQ to XML (formerly XLinq) { Queries performed against the XML source}
 
I hope few above lines increase your concrete knowledge about Microsoft LINQ and now we write some code snippet of LINQ.
 
1. Code Snippet
int[] nums = new int[] {0,1,2};var res = from a in nums             where a < 3             orderby a             select a;foreach(int i in res)    Console.WriteLine(i);
Output:012
 
 
All SQL Operates are available in LINQ to Object like Sum Operator in the following code.
 
2. Code Snippet
int[] nums = new int[] {2,4,6,2};int result = nums.Sum();Console.WriteLine(result);

Output:
1
2

One thing that I want to share with you guys is LINQ to Object support querying against any object that inherits from IEnumerable (all .Net collection inherits from IEnumerable interface). LINQ to Object provided main types of Operator Type that are give below.
 
 
Operator Types
Operator Name
Aggregation
  • Aggregate
  • Average
  • Count
  • LongCount,
  • Max,
  • Min,
  • Sum
Conversion
  • Cast,
  • OfType,
  • ToArray,
  • ToDictionary,
  • ToList,
  • ToLookup,
  • ToSequence
Element
  • DefaultIfEmpty,
  • ElementAt,
  • ElementAtOrDefault,
  • First,
  • FirstOrDefault,
  • Last,
  • LastOrDefault,
  • Single,
  • SingleOrDefault
Equality
  • EqualAll
Generation
  • Empty,
  • Range,
  • Repeat
Grouping
  • GroupBy
Joining
  • GroupJoin,
  • Join
Ordering
  • OrderBy,
  • ThenBy,
  • OrderByDescending,
  • ThenByDescending,
  • Reverse
Partitioning
  • Skip,
  • SkipWhile,
  •  Take,
  •  TakeWhile
Quantifiers
  • All,
  • Any,
  • Contains
Restriction
  • Where
Selection
  • Select,
  • SelectMany
Set
  • Concat,
  • Distinct,
  • Except,
  • Intersect,
  • Union
 
To the good use of above operator types I need samle patient class so here it
using System;
 
public class Patient
{
    // Fields
    private string _name;
    private int _age;
    private string _gender;
    private string _area;
    // Properties
    public string PatientName
    {
        get { return _name; }
        set { _name = value; }
    }
 
    public string Area
    {
        get { return _area; }
        set { _area = value; }
    }
    public String Gender
    {
        get { return _gender; }
        set { _gender = value; }
    }
    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}
 
Here is my code that intiliaze patients object with following data.
 
List<Patient> patients = new List<Patient> {
           new Patient { PatientName="Ali Khan", Age=20, Gender="Male" , Area = "Gulshan"},
           new Patient { PatientName="Ahmed Siddiqui", Age=25 ,Gender="Male", Area = "NorthKarachi" },
           new Patient { PatientName="Nida Ali", Age=20, Gender="Female", Area = "NorthNazimabad"},
           new Patient { PatientName="Sana Khan", Age=18, Gender="Female", Area = "NorthNazimabad"},
           new Patient { PatientName="Shahbaz Khan", Age=19, Gender="Male", Area = "Gulshan"},
           new Patient { PatientName="Noman Altaf", Age=19, Gender="Male", Area = "Gulshan"},
           new Patient { PatientName="Uzma Shah", Age=23, Gender="Female", Area = "NorthKarachi"}};
 
Patient p = new Patient();
        p.Age =33; p.Gender = "male";
        p.PatientName = "Hammad Ali"; 
        p.Area = "Defence";         
        patients.Add(p);


This code snippet fetch those records whose gender is equal to “Male”.
 
   gdView.DataSource = from pa in patients
                        where pa.Gender == "Male"
                        orderby pa.PatientName, pa.Gender, pa.Age
                        select pa;
   gdView.DataBind();
 
The following code snippet uses the selection operator type, which brings all those records whose age is more than 20 years.
 var mypatient = from pa in patients
                  where pa.Age > 20
                  orderby pa.PatientName, pa.Gender, pa.Age
                  select pa;
       
        foreach(var pp in mypatient)
        {
        Debug.WriteLine(pp.PatientName + " "+ pp.Age + " " +          pp.Gender);
        }
 The following code snippet uses the grouping operator type that group patient data on the bases area. 
var op = from pa in patients
group pa by pa.Area into g
select new {area = g.Key, count = g.Count(), allpatient = g};
 
 foreach(var g in op)
 {
    Debug.WriteLine(g.count+ "," + g.area);
    foreach(var l in g.allpatient)
     {
       Debug.WriteLine("\t"+l.PatientName);
     }
 }
This code snippet determine the count of those records, which lay in above 20 years. 
int patientCount = (from pa in patients
                    where pa.Age > 20
                    orderby pa.PatientName, pa.Gender, pa.Age
                    select pa).Count();

All the above codes are few example of LINQ to Object technique of LINQ. In my up coming post you will see both LINQ to SQL and LINQ to XML code snippets.
 

AutoComplete Extender

<asp:TextBox ID="txtAuto" runat="server"></asp:TextBox>
     <div id="Panel">
                            </div>
          <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" CompletionInterval="0"
                                CompletionListElementID="Panel" CompletionSetCount="12" EnableCaching="true"
                                MinimumPrefixLength="1" ServiceMethod="GetProductList" 
                                ShowOnlyCurrentWordInCompletionListItem="true" TargetControlID="txtAuto"
                               >
                            </asp:AutoCompleteExtender>
                            <%-- <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtAuto"
MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" ServiceMethod="GetProductList" >
</asp:AutoCompleteExtender>--%>
                            </br>
                            <asp:Button ID="btnSubmitt" runat="server" Text="Submitt"  OnClick="btnSubmitt_Click"  />
                            </br>
                           
                            <asp:Label ID="lblLocation" runat="server"></asp:Label></br>
                            <asp:Label ID="lblLevel" runat="server"></asp:Label>
    </div>

........................................................

 [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static string[] GetProductList(string prefixText)
        {

            string connString = "";

            string path = @"C:\Test\Company.xls";
            //Connection String to Excel Workboo
            //if (strFileType.Trim() == ".xls")
            //{
           // connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";

            connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            //}
            //else if (strFileType.Trim() == ".xlsx")
            //{
            //    connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            //}
         //  string query = "SELECT [Company] FROM [Sheet1$] where Company like '" + prefixText + "'";
           string query = "SELECT [Company] FROM [Sheet1$] where Company like '" + prefixText + "'+'%'";

            OleDbConnection conn = new OleDbConnection(connString);
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            else
            {

            }
            OleDbCommand cmd = new OleDbCommand(query, conn);
            OleDbDataAdapter da = new OleDbDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds);

                                  
            DataTable dt = ds.Tables[0];

            List<string> txtProductName = new List<string>();
            String dbValues;

            foreach (DataRow row in dt.Rows)
            {

                dbValues = row["Company"].ToString();
                dbValues = dbValues.ToLower();
                txtProductName.Add(dbValues);
            }

            return txtProductName.ToArray();
        }

        protected void btnSubmitt_Click(object sender, System.EventArgs e)
        {
            string connString = "";

            string path = @"C:\Test\Company.xls";
            //Connection String to Excel Workboo
            //if (strFileType.Trim() == ".xls")
            //{
            // connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";

            connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            //}
            //else if (strFileType.Trim() == ".xlsx")
            //{
            //    connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            //}
            //  string query = "SELECT [Company] FROM [Sheet1$] where Company like '" + prefixText + "'";
            string query = "SELECT [Location],[Level] FROM [Sheet1$] where Company = '" + txtAuto.Text.Trim() + "'";

            OleDbConnection conn = new OleDbConnection(connString);
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            else
            {

            }
            OleDbCommand cmd = new OleDbCommand(query, conn);
            OleDbDataAdapter da = new OleDbDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {

                lblLocation.Text = Convert.ToString(ds.Tables[0].Rows[0]["Location"]);
                lblLevel.Text = Convert.ToString(ds.Tables[0].Rows[0]["Level"]);
            }

        }