Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Linq to XML

Introduction:

For any application common approach is use database or XML documents to store backend data.

a. LINQ provides LINQ to SQL component to directly manipulate relational data, you can perform linq queries on Data directly.

b. For XML document .net framework provided LINQ to XML interface that enables In-memory XML document modification.

In this article I will describe LINQ to XML in detail with some sample examples.

What is LINQ to XML?

LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the .NET Framework programming languages.

LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory. You can query and modify the document, and after you modify it you can save it to a file or serialize it and send it over the Internet. However, LINQ to XML different from DOM.

Using LINQ to XML, you can

a. Load XML from files or streams.
b. Serialize XML to files or streams.
c. Create XML from scratch by using functional construction.
d. Query XML using XPath-like axes.
e. Manipulate the in-memory XML tree by using methods such as Add, Remove, ReplaceWith, and SetValue.
f. Validate XML trees using XSD.
g. Use a combination of these features to transform XML trees from one shape into another.

Reference: https://msdn.microsoft.com

Why LINQ to XML?

LINQ to XML enables you to create and modify XML documents easily by using LINQ query expressions instead of XPath or XQuery.

Compared with classic complex XML parsing approach LINQ to XML expressions are easy to read xml document and modify XML document.

Advantages using LINQ to XML:

1. LINQ to XML makes XML easier by providing a query experience that is similar to SQL.
2.   Allows to use query result as parameters to XElement and XAttribute object constructors enables a powerful approach to creating XML trees.
This approach, called functional construction, enables developers to easily transform XML trees from one shape to another.
3. Main advantage of LINQ to XML is its integration with LINQ, This integration allows you to write queries on the in-memory XML document to retrieve collections of elements and attributes.
   var result = xdoc.Descendants("Types")
                 .Descendants("Animals")
                 .Descendants("Tab")
                 .Elements("Dogs")
                 .Where(n => n.Attribute("id").Value == "1");
4. Easy to create XML trees with LINQ to XML.
5. Compiled and in memory use, so it runs faster.
6. Allows for better string manipulation.
7. Ability to work directly with XML elements instead of creating a container XML document, as required with W3C DOM.
8. In-memory XML document modification that is powerful, yet simpler to use than XPath or XQuery.
9. You can perform sorting, grouping on xml data.

LINQ to XML Example with Sorting Data:

Following example LINQ to xml query sort’s student’s xml data by year in ascending order.

XML:

<?xml version="1.0" encoding="UTF-8"?>
<
Collage>
  <
Students>
    <
Student>Shourya</Student>
    <
Year>2014</Year>
    <
teacher>Nagnath</teacher>
  </
Students>
  <
Students>
    <
Student>Shrad</Student>
    <
Year>2015</Year>
    <
teacher>Girish</teacher>
  </
Students>
  </
Collage>

LINQ to XML Query:

IEnumerable<decimal> Students =
 
         from el in doc.Elements("Students")
 
         let year = (decimal)el.Element("Year")
 
         orderby year
 
         select year;
           foreach (decimal student in Students)
               Console.WriteLine(student);

 

LINQ to XML methods with use of extension method:

In following example count method is used with XML document  

var doc = XDocument.Load("~/nmk/students.xml");
int descendantsNodes =doc.Descendants().Count(); // counts ALL descendants elements
int childNodes = doc.Root.Elements().Count(); //counts direct children of the root element


User Defined Extension methods with LINQ to XML:

In following example I have created extension methods for data casting, those methods I used with LINQ to XML query.

  var products =
               from elem in xElem.Descendants("Product")
               orderby elem.Attribute("ProductName").Value
               select new Product
               {
                   ProductId = elem.Attribute("ProductId").GetAsInteger(),
                   ProductName = elem.Attribute("ProductName").GetAsString(),
                   Category =
                      elem.Attribute("Category").GetAsString(),
                   Price = elem.Attribute("Price").GetAsDecimal()
               };


User Defined Extension method:

public static string GetAsString(this XAttribute attrbute)
  {
    string ret = string.Empty;
 
    if (attrbute != null && !string.IsNullOrEmpty(attrbute.Value))
    {
      ret = attrbute.Value;
    }
 
    return ret;
  }

 

Using existing .net Framework provided extension methods with LINQ to XML:

Following LINQ to XML query example returns valid products data for existing categories only

var ValidProductsDeatils = xElem
 .Element("Products")
 .Elements("Product")
 .Where
 (
     x =>  x .Elements("Category")
     .Where
     (
         z => z.Attribute("Id").Value !="0"
     )
     .Select
     (
         z =>
         z.Attribute("Name").Value
     ).SingleOrDefault()=="true"
 );
 

Linq to Dataset

Introduction:

Previously I written two articles on linq features LINQ to SQL and Linq to Objects, I specified in first article I will continue writing some more articles on LINQ features.

In this article I will describe in detail LINQ to Dataset in detail with some sample examples.

 What is LINQ to dataset?

LINQ to Dataset provides the easier and faster approach to query over data cached in a DataSet object.

LINQ to DataSet can also be used to query over data that has been consolidated from one or more data sources.

For example querying data on actual data and intermediate cached data source in financial web application, such scenarios required to create financial reports.

Following diagram explain relationship between LINQ to Dataset to ADO.NET 2.0 and Database.

                       

Why LINQ to Dataset?

LINQ to Dataset allows developers to write queries from the programming language itself, instead of using separate query language.

Programming query languages who can now take advantage of the compile-time syntax checking, static typing, and IntelliSense support provided by the Visual Studio in their queries,this is especially useful for Visual Studio developers.

Advantages using Linq to Dataset:

1. Easy and readable.

2. No need to learn separate query languages like SQL (Structured query language), you can use visual studio programming language.
3.  You can use linq on two different datasets or you can retrieve some distinct values from dataset using Linq To Dataset.
4. You can use Sql queries to retrieve dataset but you can’t use SQL queries to retrieve value from dataset, in classic programming .net provides ado.net objects but with Linq to Dataset approach you can retrieve some distinct values from dataset.

 LINQ to Dataset Single table Queries:

The following obtains valid Products from the “C4Test” sample database using LINQ to dataset query.

  DataSet ProductsData = ProductDataAccess.GetProductDetails();  
  DataTable Products = ProductsData.Tables["Products"];

 

          var ValidProducts =
              from product in Products.AsEnumerable()
              where product.Field<string>("ProductName") != string.Empty
              && product.Field<int>("CategoryId") != 0
              select new
              {
                  ID =
                      product.Field<int>("ID"),
                  Name =
                      product.Field<int>("ProductName"),
                  Price =
                      product.Field<int>("Price")
              };

 

LINQ to Dataset Cross table query Example:

The following example performs a classic join (SQL join) of the Products and Categories tables from the “C4Test” sample database to obtain valid product details with categories.
LINQ framework provides two join operators, Join and GroupJoin. These operators perform equi-joins: that is, joins that match two data sources only when their keys are equal.
DataSet ProductsData = ProductDataAccess.GetProductDetails();
DataSet CategoriiesData = ProductDataAccess.GetProductCategories();
 
DataTable Products = ProductsData.Tables["Products"];
DataTable Categories = CategoriiesData.Tables["Categories"];

 

           var query =
               from product in Products.AsEnumerable()
               join category in Categories.AsEnumerable()
               on product.Field<int>("CategoryId") equals
                   category.Field<int>("ID")
               where product.Field<string>("ProductName") != string.Empty
               && product.Field<int>("CategoryId") != 0
               select new
               {
                   ID =
                       product.Field<int>("ID"),
                   Name =
                       product.Field<int>("ProductName"),
                   Category =
                       category.Field<string>("CategoryName"),
                   Price =
                       product.Field<int>("Price")
               };

 

Creating a DataTable from a Query (LINQ to Dataset):

The following example queries the Categories table for valid categories and uses the CopyToDataTable method to create a DataTable from that query.
 DataSet CategoriiesData = ProductDataAccess.GetProductCategories();
 DataTable Categories = CategoriiesData.Tables["Categories"];

 

  // Query the Categories table for only valid categories
  IEnumerable<DataRow> ValidCategories =
           from category in Categories.AsEnumerable()
           where category.Field<string>("CategoryName")!=string.Empty
           select category;
 
   // create a table from the query.
   DataTable NewValidDataTable = ValidCategories.CopyToDataTable<DataRow>();

 

Conclusion:

LINQ to Dataset allows developers to write queries from the programming language itself, instead of using separate query language.

 You can perform joins on different tables and you can retrieve only required data from different data sources.

 

Linq to Objects

Introduction

Previously I written article on .net framework component LINQ to SQL, I specified in that article I will continue writing some more articles on LINQ features.

In this article I will describe LINQ to Objects in detail with some sample examples.

What is LINQ to Objects?

LINQ to objects provides the ability to query IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML.

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey, TValue>. The collection may be user-defined or may be returned by a .NET Framework API.

Why LINQ to Objects?

In classic old programming you had to write complex foreach loops that specified how to retrieve data from a collection.

Linq approach provides declarative code that describes what you want to retrieve.

Advantages using LINQ to Objects:

1. Easy and readable.
2. They provide powerful filtering, ordering, and grouping capabilities with a minimum of application code.
3. Removes unwanted complex code, reduce code redundancy.  
4.  Reusable code with some modifications or no modifications.

5. LINQ queries provides following advantages on old foreach loop:

 a. More concise, easy and readable, especially when filtering multiple conditions.
 b. Provide powerful filtering, ordering, and grouping features with reduced code.
 c. They can be ported to other data sources with little or no modification.

Generic list Linq to Objects Example:

In following example I used linq to objects query on categories generic list to retrieve only valid product categories.

  //Generic Categories list data
  List<ProductCategory>categories = ProductDataAccess.GetProductCategories();


 
  //Returns Records (products) that satisfy where condition Category name not empty
  var MobileCategory = from c in categories
                       where c.CategoryName != ""
                       select c;

 

IEnumerable collection linq to objects Example:

In following example I used linq to objects query on products IEnumerable collection to retrieve only valid products.
var ValidProductsByAscending = from p in products
                               where p.ProductName != string.Empty
                               orderby p.ProductName ascending
                               select p;

Query a String Array using LINQ to Objects:

In following example LINQ to Objects is used to query this string array to find and return a subset of the array in the form of all students with name contains with the word “kendre”.

string[] Students = { "Shouarya Kendre", "Anushka Kendre", "Aditya Kendre",
                   "Rudra Sarode", "Sanskruti Kendre", "Akshara Kendre","Sharad Sangle"}

 

var StudentsWithSurnameKendre = from s in Students
           where s.Contains("Kendre")
           select s;

 

Query an ArrayList using LINQ to objects:

The following example shows a simple query over an ArrayList. Linq to objects query retrieves those students who scored min 60 marks in all subjects.

 

ArrayList arrList = new ArrayList();
           arrList.Add(
               new Student
               {
                   FirstName = "Shouarya",
                   LastName = "Kendre",
                   Scores = new int[] { 98, 92, 81, 60 }
               });
           arrList.Add(
               new Student
               {
                   FirstName = "Rudra",
                   LastName = "Sarode",
                   Scores = new int[] { 75, 84, 91, 39 }
               });
           arrList.Add(
               new Student
               {
                   FirstName = "Sanskruti",
                   LastName = "Kendre",
                   Scores = new int[] { 88, 94, 65, 91 }
               });
           arrList.Add(
               new Student
               {
                   FirstName = "Aditya",
                   LastName = "Mundhe",
                   Scores = new int[] { 97, 89, 85, 82 }
               });

 

   var query = from Student student in arrList
              where  student.Scores[0] > 59 
                        && student.Scores[1] > 59 
                        &&student.Scores[2] > 59 
                        && student.Scores[3] > 59
              select student;