Loading ...

Introduction of LINQ | CodeAsp.Net

Introduction of LINQ

  •  /5
    Avg: 0 / 5 (0votes)
  • (0)
  • (9006)
Published: 4/2/2012 by Vijendra Shakya


LINQ provides uniform way to perform action on any object which Implements the IEnumerable<T> OR IQueryable<T> interface with different type of data sources.”

LINQ is the new feature which is available in .Net 3.0 and onwards.LINQ stands for “Language Integrated Query”. LINQ introduces in new version of Microsoft Visual Studio code named “Orcas”, it is the set of features such as Lambda Expression, Extension Methods and and query comprehensions that enable compilers to understand and implement query logic over in-memory collections of objects.
Fundamentally the function of LINQ is about Data manipulation i.e. retrieving data from different data source in a unified pattern. LINQ allow us to write your logic in the language of your choice (C#, VB). LINQ provides all the features which a Data source (SQL, Oracle, XML, XQuery etc.) provide with the help of language of your choice.

“LINQ provides uniform way to perform action on any object which Implements the IEnumerable<T> OR IQueryable<T> interface with different type of data sources”.

LINQ does not force to follow any specific articture.LINQ is a programming modal that gives us a platform to write queries in the .NET languages.LINQ comes under the “System.Linq” namespace.


IEnumerable<T> VS  IQueryable<T>:
In Linq there are few providers available with .Net Framwork.
For example: LINQ To Objects,LINQ To XML,LINQ To SQL
IQueryable<T> inherite the IEnumerable<T> interface, so anything you can do with a IEnumerable<T>, you can also do with an IQueryable<T>.
IEnumerable<T> is outstanding when working with sequence  that are repeated  “In-Memory” objects, but IQueryable<T> allows for out-of memory things like a remote data source, such as a database or web service.
IEnumerable<T> just has a GetEnumerator() method that returns an Enumerator<T> for which you can call its MoveNext() method to iterate through a sequence of T i.e. IEnumerable<T> is the forward only collection. IQueryable<T> have two properties which IEnumerable<T> does not have are Query Provider(LINQ TO SQL) and query expression representing the IQueryable<T> object as a runtime-traversable.
The query expression can be a constant expression of the object itself or a more complex tree of a composed set of query operators and operands. The query provider's IQueryProvider.Execute() or IQueryProvider.CreateQuery() methods are called with an Expression passed to it, and then either a query result or another IQueryable is returned, respectively
Following is the the LINQ Statement which returns IEnumerable<T>.
IEnumerable<T> works in steps.
Here we are using following DataSource Method:

string[]linqDataSource = {"Hello","LINQ","This","Is","My","First","LINQ","Example"};

 IEnumerable<string> linqQuery = from query in linqDataSource
                                where query.Length > 5
                                select query;

1.This Query create a list of “query”  depending on “where” .

2.This Query creates another list for “select”.


LINQ TO Objects

 This is the deportment of LINQ To Object and LINQ To XML.
LINQ To SQL uses IQueryable<T> interface, this interface inherit from IEnumerable<T> interface.LINQ To SQL generate the T-SQL at the backend. IQueryable<T> analyze and generate the query in one snap and gives us the whole resulted data. 



There are 3 basic operations in the LINQ:
1. Find the Data Source
2. Create the Query
3. Execute the Query

Following is the structure of basic operation.


Query Expression


Example: following is the 3 steps which is required to finding the result through LINQ.
step 1 : In LINQ first step is specify the Data Source, following is a collection of string as a data source.

 string[]linqDataSource = {"Hello","LINQ","This","Is","My","First","LINQ","Example"};

Step 2: After finding the data source now we need to create the query over this data source.

IEnumerable<string> linqQuery = from result in linqDataSource                     

 select result;

Step 3: LINQ Query executes in foreach statement, the execuatation of query start when itrate over the query varible in foreach statement. Queries that perform the aggregate operations,no need to execute those queries  in foreach statement those queries Immediate Execute.
Example : Count(),Max(),Min(),Average(),sum() etc.

foreach (var result in linqQuery)

Finally now we have combined all these 3 steps.

string[]linqDataSource = {"Hello","LINQ","This","Is","My","First","LINQ","Example"};  

IEnumerable<string> linqQuery = from result in linqDataSource

  select result;


 foreach (var result in linqQuery)


   Response.Writeresult+" ");


The output of this LINQ example is:
Hello LINQ  This Is My First LINQ Example

 Following is the execution structure of the LINQ query.


LINQ EXecution Steps



LINQ  Architecture:


LINQ Architecture

According to LINQ Architecture currently LINQ supports C# 3.0 and onwards version and VB 9.0 programming language.
LINQ Supports 3 LINQ Enabled Data Source
1. LINQ to Objects
3. LINQ to XML

Linq to Objects allows us to write the “queries” on the Collection of Objects; these queries execute against the “in-memory” collection which implements IEnumerable or IQueryable interface.Following is the Standard Query operator which comes under the LINQ To Objects.

Standard Query Operator:This is an application by which we can write the query against the array or collection. The Standard Query Operators operate on sequences. Any object that implements the interface IEnumerable<T> for some type T is considered a sequence of that type.
Following is some mostly used standard query operator.
Here we are using following two Data source :

string[]linqDataSource = {"Hello","LINQ","This","Is","My","First","LINQ","Example"};

This datasource we use for string manuplation. For Integer realted calculation we are using:

int[]LinqIntDataSource = { 1, 3, 4, 2, 5, 7, 3, 8, 9, 0, 1, 5, 6 };

Where(): This is a Restriction operator.It is used to filter the element from the datasource.

<string> where = from WhereExample in linqDataSource

                            where WhereExample.Length==2

                            select WhereExample;

  foreach (var WhereExample in where)


   Response.Write(WhereExample + " ");


Output will be: Is My

Select(): This is a Projection operator. It is used to get the element from the datasource.    
IEnumerable<bool> selectRecord = from SelectExample in                    linqDataSource  select SelectExample;
foreach (var SelectExample in selectRecord)


    Response.Write(SelectExample + " ");


 Output will be: Hello LINQ  This Is My First LINQ Example

Skip(): This is a
Partitioning operator which is used to Skip number of values from the given sequence and return remainder of the sequence.
IEnumerable<string> skip = from SkipExample in linqDataSource.Skip(4)  

select SkipExample;
// here 4 means The number of elements to skip before returning the remaining elements.

foreach (var SkipExample in skip)


  Response.Write(SkipExample + ", ");


Output will be: My, First, LINQ, Example

Take(): The Take operator returns a given number of elements from a sequence and then skips the remainder of the sequence.
IEnumerable<string> take = from TakeExample in linqDataSource.Take(3)

select TakeExample;

foreach (var TakeExample in take)


  Response.Write(TakeExample + ", ");


Output will be: Hello, LINQ, This, Is, My

First(): This is Element operator. First operator gives the first element of a sequence.


string FirstExample = linqDataSource.First();


Output will be: Hello

FirstOrDefault(): The FirstOrDefault operator returns the first element of a sequence, or returns a default value if the sequence not contains no element.

string firstOrDefault = linqDataSource.FirstOrDefault();


Output will be: Hello

Last(): The Last operator returns the last element of a sequence.

string LastExample = linqDataSource.Last();


Output will be: Example

LastOrDefault():The LastOrDefault operator returns the last element of a sequence, or returns  a default value if no element is found in sequence.


string lastOrDefault = linqDataSource.LastOrDefault();


Output will be: Example

Distinct(): This operator is SET operator, this removes duplicate values from the given Sequence.

IEnumerable<int> distinct = from DistinctExample in LinqIntDataSource.Distinct()

                          select DistinctExample;

            foreach (var DistinctExample in distinct)


                Response.Write(DistinctExample + “, “);


Output will be: 1, 3, 4, 2, 5, 7, 8, 9, 0, 6

Contains():This is Quantifiers operator , which checks whether a sequence contains a given element or not.it returns true if sequence contains a specific element else return false.

bool anyExample = LinqIntDataSource.Contains(4)


Output will be: True

Count(): The Count operator counts the number of elements in a sequence with a return type of int.This Operator is the Aggregate operator.


int countExample = LinqIntDataSource.Count();


Output will be: 13

Average() : The Average operator computes the average number from the sequence of integer values, it returns result as a double type.

double averageExample = LinqIntDataSource.Average();


Output will be: 4.15384615384615

Max(): This operator finds the maximum number from the sequence of numeric values.

int maxExample = LinqIntDataSource.Max();


Output will be:  9

Min(): This operator finds the minimum number from the sequence of numeric values.

 int minExample = LinqIntDataSource.Min();


 Output will be: 0

Sum(): Sum operator determines the sum of numbers from the sequence of numeric values.

int sumxample = LinqIntDataSource.Sum();


Output will be: 54

ANY(): It returns true if sequence contains any element else return false.

bool anyExample = LinqIntDataSource.Any();


Output will be: True 


There are 3 parts of LINQ to ADO.NET
1. LINQ TO SQL : LINQ to SQL(formally known as DLinq) is an API for working with SQL server database. It is an object relational mapping(ORM) that comes under the .NET framework name “ORCAS”,Orcas allows you to modal a relational database with .Net classes.We can Insert,Update,Delete and select the data with the help of LINQ
. LINQ also support the StoreProcedure, Views, Transactions. LINQ to SQL use the IQueryable<T> interfrece,It is compratible with ADO.NET 2.0. With the help of LINQ to SQL we can generate dynamic SQL queries based on your programming language.

Note: It only works with SQL Server and SQL Express

Following is the Modeling Database structure using LINQ To SQL:


LINQ TO SQL Modeling Design



This modeling design have 2 entity classes:

1. Product 2. Category.

The property of the class reprenents the column name of the Database table.Every instance of the class entity represents the row of table.

Following is some sample example of LINQ To SQL:

1. Inserting Category In the Category Table
LinqToSqlDataContext db = new LinqToSqlDataContext();
Category category = new Category


    CategoryName = "Men’s Cloth",

    IsActive = true




This will insert a row in the category Database table.

For inserting the Product in Product table:
LinqToSqlDataContext db = new LinqToSqlDataContext();

Product product = new Product


   CategoryID = 1,

   ProductName = "T-Shirt",

   UnitPrice = 4.23m



This will insert a row in the product table.

For selecting all the records from the Database which have CategoryId =1 we can do this as follows

LinqToSqlDataContext db = new LinqToSqlDataContext()

var products = from p in db.Products

               where p.Category.CategoryID == 1

               orderby p.ProductID descending

               select p;

This example returns all the rows from the product table where  CategoryID=1

simple Join:
LinqToSqlDataContext db = new LinqToSqlDataContext()               

var products = from p in db.Products

               join c in db.Categories





               select p;


Find Top 10 Products :
LinqToSqlDataContext db = new LinqToSqlDataContext()

var products = from p in db.Products.Take(10)

                               orderby p.ProductID

                               select p;


In LINQ To SQL Storeprocedure treated as a “methods”.             
2. LINQ To DataSet: LINQ to Dataset is the “In-Memory” representation of Data, you can say it is an “In-Memory” relational database. LINQ to dataset makes query fast and easier over dataset objects.

Note: DataTable did not have the implementation of IEnumerable<T> interface.DataTable have the AsEnumerable which returns an objects that object have the implementation of IEnumerable<T> interface.

3. LINQ To Entities : Entity framwork allows us to work with domain specific objects and properti. It allows us to create easy,fast, flexible and strongly type queries aganinst the Framwork.The quries written in programming language.

LINQ to XML is the part of .net 3.5 it comes under System.Xml.Linq
namespace, it provides the “In-Memory” XML programming interface on the .NET programming language.In LINQ to XML we are writing the queries over XML,we can read write and create XML based data through LINQ TO XML. XElement, XAttribute and XName are commonly used methods in LINQ To XML, XElemet represents the element of the XML,XAttribute represents the attribute and XName is used for the name of the element,attributes and can contains the namespace information.
Following is the some important methods and Properties of LINQ  to XML.

Add(): Add an Element to the XML document.

AddFirst(): Adds the first children in the document or element.

Gives the First Child Node of the current node.

LastNode(): returns the Last Child Node of the current node.

NextNode():returns the next Child Node of the current node.

PreviousNode(): Gives the Previous sibling Node of the current node.

Root(): Return the Root node of the XML element.

RemoveNode(): Remove the node from the XML element.

FirstAttribute(): Gives the firstAttribute of the current element.

We can create the XML file as following way:

           XDocument documnet = new XDocument(

           new XDeclaration("1.0", "utf-8", "yes"),

           new XComment("Sample of Product XML File"),

           new XElement("Products",

               new XElement("Product",

                   new XAttribute("ProductID", 1),

                   new XAttribute("CategoryID", 1),

                   new XAttribute("ProductName", "T-Shirt"),

                   new XAttribute("UnitPrice", 4.25),

                   new XAttribute("Quantity", 20),

                   new XAttribute("IsInStock", true)),


               new XElement("Product",

                   new XAttribute("ProductID", 2),

                    new XAttribute("CategoryID", 3),

                   new XAttribute("ProductName", "Shose"),

                   new XAttribute("UnitPrice", 5.50),

                   new XAttribute("Quantity", 25),

                   new XAttribute("IsInStock", false))


Out will be:

<!--Sample of Product XML File-->


  <ProductProductID="1"CategoryID="1"ProductName="T-Shirt"UnitPrice="4.25"Quantity="20"IsInStock="true" />

  <ProductProductID="2"CategoryID="3"ProductName="Shose"UnitPrice="5.5"Quantity="25"IsInStock="false" />


Note: This out put we can not see on the web page, just find out put in xml file.

If we want to select the data from the XML file we can do this as follows:

XElement productList = XElement.Load("D://product.xml ");

var products = from product in


  select new


        ProductId = (string)product.Attribute("ProductID"),

        ProductName = (string)product.Attribute("ProductName"),

        UnitPrice = (string)product.Attribute("UnitPrice")



  foreach (var product in products)


       Response.Write(product + "<br/>");


Out put Will be:
{ProductId = 1, ProductName = T-Shirt, UnitPrice = 4.25}
{ProductId = 2, ProductName = Shose, UnitPrice = 5.5}

Simple Join in LINQ to XML:
suppose we have another XML file category.xml

<!--Sample of Product Category XML File-->

CategoryCategoryID="1"CategoryName="T-Shirt"IsActive="true" />

<CategoryCategoryID="2"CategoryName="Fruit"IsActive="true" />


Now implement join with above used product.xml and category.xml

XElement productList = XElement.Load(path + "Product.xml");

XElement categiryList = XElement.Load(path+"Category.xml");

var results = from product in productList.Descendants("Product")

              join category in categiryList.Descendants("Category")

              on (string)product.Attribute("CategoryID")

              equals (string)category.Attribute("CategoryID")

 select new


       ProductId = (string)product.Attribute("ProductID"),

       ProductName = (string)product.Attribute("ProductName"),

       CategoryName = (string)category.Attribute("CategoryName")


foreach (var result in results)




Output will be:

{ProductId = 1, ProductName = T-Shirt, CategoryName = T-Shirt}

Anonymous methods concept comes in C# 2.0, in which we can write a “In-line” code this concept called Lambda Expression,it contains expression and statemnet, we can create an expression tree or delegate with lambda expression.Lambda expression use the Lambda operator =>, read as a “goes to”.On the left of the Lambda operator is Input parametar and  on the right side is lambda expression.for example S => S+1, here S is the input parameter and S+1 is the lambda expression.


Lembda Expression


Please leave your valuable comments on this article. :)




Comments (4)

That is very helpful for developer keep it up vij
Deepak Nigam said:
nice job...will be looking some more from you.
naval pandey said:
nice article good for the beginner 
sandeep kumar said:
Nice article Give Some advance Feature,example of LINQ To Entities

Top articles

Quick Vote

What kind of email newsletter would you prefer to receive from CodeAsp.Net?