Monday, January 18, 2016

LINQ Syntex

LINQ Syntax

There are two basic ways to write a LINQ query:
  1. Query Syntax or Query Expression Syntax
  2. Method Syntax or Method extension syntax or Fluent

Query Syntax:

Query syntax is similar to SQL (Structured Query Language) for a database. It is defined within the C# or VB code.
from <range variable> in <collection>
<filter, joining, grouping, aggregate operators etc.> <lambda expression>
<select or groupBy operator> <formulate the result>

Example
int[] numbs = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
var numQry = from num in numbs
             where (num % 2) == 0
             select num;

Query Syntax starts with from clause followed by Range variable. After from clause, you can use different standard query operations such as filter, group, joins etc. there are 50 standard query operators available in LINQ. In Above Example we used where operator to filter even numbers. LINQ always ends with select or group by clause. The select is used to get data from source. You can have whole object or some properties of the object in select section.


LINQ Method Syntax

Method syntax (also known as fluent syntax) uses extension methods included in the Enumerable or Queryable static class, similar to how you would call the extension method of any class.
The following figure illustrates the structure of LINQ method syntax.

Example
IList<Student> studentList = new List<Student>() {
    new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
    new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 } ,
    new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } ,
    new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
    new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};

// LINQ Method Syntax to find out teenager students
var teenAgerStudents = studentList.Where(s => s.Age > 12 && s.Age < 20)
                                  .ToList<Student>();


As you can see in the above figure, method syntax comprises of extension methods and Lambda expression. The extension methods Where and ToList are defined in the Enumerable class.

LINQ Architecture

LINQ Architecture in .NET

LINQ has a 3-layered architecture in which the uppermost layer consists of the language extensions and the bottom layer consists of data sources that are typically objects implementing IEnumerable<T> or IQueryable<T> generic interfaces. The architecture is shown below in Figure.


LINQ to Objects deals with in-memory data. Any class that implements the IEnumerableinterface (in the System.Collections.Generic namespace) can be queried with Standard Query Operators.

LINQ to ADO.NET
(also known as LINQ enabled ADO .NET) deals data from external sources, basically anything ADO.NET can connect to. Any class that implements IEnumerableor IQueryable (in the System.Query namespace) can be queried with Standard Query Operators. The LINQ to ADO.NET functionality could be achieved by using System.Data.Linq namespace.

LINQ to XML is a comprehensive API for in-memory XML programming. Like the rest of LINQ, it includes Standard Query Operators, and it can also be used in concert with LINQ to ADO.NET, but its primary purpose is to unify and simplify the kinds of things that disparate XML tools, like XQuery, XPath and XSLT are typically used to do. The LINQ to XML functionality could be achieved by using 
System.Xml.Linq namespace.

Linq Introduction

LINQ Introduction

Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.

Three Parts of Query operation

All LINQ query operations consist of three distinct actions:
1.       Obtain the data source.
2.       Create the query.
3.       Execute the query.
The following example shows how the three parts of a query operation are expressed in source code. The example uses an integer array as a data source for convenience; however, the same concepts apply to other data sources also.

Example

class LINQExample
{       
    static void Main()
    {
        // The Three Parts of a LINQ Query:
        //  1. Data source.
        int[] numbs = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

        // 2. Query creation.
        // numQuery is an IEnumerable<int>
        var numQry =
            from num in numbs
            where (num % 2) == 0
            select num;

        // 3. Query execution.
        foreach (int num in numQry)
        {
            Console.Write("{0,1} ", num);
        }
    }
}


Data Source

In above example the data source is an inter array. Linq To SQL and LINQ to XML are also available
to fetch data from different sources

Types of LINQ
The types of LINQ are mentioned below in brief.
·         LINQ to Objects
·         LINQ to XML(XLINQ)
·         LINQ to DataSet
·         LINQ to SQL (DLINQ)
·         LINQ to Entities
Query

The query specifies what information to retrieve from the data source or sources. Optionally, a query also specifies how that information should be sorted, grouped, and shaped before it is returned. A query is stored in a query variable and initialized with a query expression. 

In above example it retrieve all even numbers from integer array. The query expression contains three clauses: from, where and select. The from specify the data source, where specify the
filters and select specify the type of returned elements


Query Excution

Deferred Execution

The query variable itself only stores the query commands. The actual execution of the query is deferred until you iterate over the query variable in a foreach statement. This concept is referred to as deferred execution and is demonstrated in the following example:


foreach (int num in numQuery)
{
    Console.Write("{0,1} ", num);
}

The foreach statement is also where the query results are retrieved. For example, in the previous query, the iteration variable num holds each value (one at a time) in the returned sequence.


Forcing Immediate Execution

Queries that perform aggregation functions over a range of source elements must first iterate over those elements. Examples of such queries are CountMaxAverage, and First. These execute without an explicit foreach statement because the query itself must useforeach in order to return a result. Note also that these tpes of queries return a single value, not an IEnumerable collection. The following query returns a count of the even numbers in the source array:

var evenNumQuery = from num in numbers
    where (num % 2) == 0
    select num;

To force immediate execution of any
query and cache its results, you can call the ToList<TSource> or ToArray<TSource> methods.


Syntax of LINQ

There are two syntaxes of LINQ. These are the following ones.
·         Lamda (Method) Syntax 
·         Example
var longWords = words.Where( w => w.length > 10);
·         Query (Comprehension) Syntax
·         Example

var longwords = from w in words where w.length > 10;