15 - LINQ in ASP.NET


15.1 Introduction to LINQ

Language Integrated Query (LINQ) is used for combining the objects and data together. The feature is added in Visual Studio 2008 and .Net framework. The query has capabilities of working with languages C# and VB. It has standard, easy to learn patterns for querying and updating data. It provides the LINQ provider assemblies to enable the use of LINQ with the .NET framework. The LINQ architecture is extensible to provide implementations to work for both XML and SQL data.

LINQ Architecture

The architecture of the LINQ is as shown below:


The LINQ to objects are used to access the memory data of the application. The class implementing IEnumerable interface can be queried using standard query operations. The LINQ to ADO.NET deals data from the external sources connected through ADO.NET. The LINQ to ADO.NET functionality can be achieved using System.Data.Linq namespace.

LINQ to XML is used for in-memory XML programming. It contains standard query operators and can be combined with LINQ to ADO.NET. The tools like XQuery, XPath, XSLT are used for achieving the task in an application. The LINQ to XML functionality can be achieved using System.Xml.Linq namespace.

The advantages of using LINQ are as follows:

  • It provides syntax highlighting and Intellisense during the development of the query
  • As it is integrated with C#, user can write code faster than the old style queries used for development
  • It provides a quick turnaround time for the development
  • The queries can be dynamically created for an application
  • It has a hierarchical feature to easily view the relationship between tables
  • It is extensible and users can use the knowledge of LINQ to make new data types
  • User can easily join multiple data sources in a single query
  • It is declarative and allows to write concise code that is easy to maintain
  • The tables can be automatically added to the class
  • The relationship can be automatically appended to the class

The disadvantages of using LINQ are as follows:

  • It does not provide clear distinguish between the tiers in an application
  • The permissions cannot be easily viewed by the user
  • The time to build small datasets is large compared to the query execution
  • There are concurrency issues with LINQ queries
  • The performance is degraded if the query is not stated correctly by the user
  • It is difficult to understand the advanced query using expressions
  • If the user changes the way to access data, recompile, version, and redeploy the assembly
  • The complete query is sent to the database increasing the traffic in the network

15.2 Syntax of LINQ

There are three ways to write LINQ query in C#. The list of the query types is as mentioned below:

  • Using query syntax
  • Using method syntax
  • Using combination of query syntax and method syntax

Using query syntax: User can write queries using query syntax to create query expressions. Some of the query types using expressions are as shown below:

      List<int> numbers1 = new List<int>() { 1,2,3,5,4};

      var number2 = from num in numbers1
      where num<2 || num>4
      select num;

In the query above, all the numbers from the list who are less than 2 and greater than 4 will be displayed.

Consider ordering in the list of variables through LINQ query, A sample code is as shown below:

     IEnumerable<int> orderQuery = from num1 in numbers1
                    where num1<2 || num1>4
                   orderby num1 ascending
                   select num1;


In the query, the numbers present in the result set will be in ascending order of the list.

Consider grouping of items present in the query list. A sample code is as shown below:

     string[ ] groupquery = {“Bread”, “Cheese”, “Butter”, “Jam”};

     IEnumerable<IGrouping<char, string>>queryFood = 
     from items1 in groupQuery
     group items1 by items1[0];

In the query, the items are grouped the food category and using the index values the items will be displayed.

Using method syntax: The query expressions are expressed as method call. The methods that return single numeric values can be used in the query. Some of the methods are Sum, Max, Min and Average. A sample code is as shown below:

     List<int> num1 = new List<int>{4,3,2,8,6};
     var avg1 = num1.Average();


In the query, the average of the numbers in the list is displayed.

Consider another example of concatenation of two lists in an application. A sample code is as shown below:

     List<int> num1 = new List<int>{4,3,2,8,6};
     List<int> num2 = new List<int>{1,5,7,9,0};

     var concatquery = num1.Concat(num2);

Using combination of query syntax and method syntax: User can implement the method syntax in the query clause. To write the query, enclose the query in parenthesis, apply a dot operator can call the method. A sample code is as shown below:    

//using an expression with method syntax

var count1 = ( from num in num1 
        where num<3 || num>4
        select num).Count();
//create a variable to store the result of the method call
IEnumerable<int> numQuery = from num in num1
                   where num <3 || num>4
                   select num;

int count2 = numQuery.Count();

In the above query, both the way to call a method are shown. User can execute the query in any format.

15.3 Example of LINQ query

Consider a class students containing properties as Name, Class and Location. Add the property values to the list object. The code behind file for it is as shown below:

public class Students
   public string Name{ get; set; }
   public string Class{ get; set; }
   public string Location{ get; set; }
   public Students()
   public static List<Students>GetItems()
    List<Students> l1 = new List<Students>();
    l1.Add(new Students{Name=”Mark”, Class=”7”, Location=”UK”});
    l1.Add(new Students{Name=”Santa”, Class=”8”, Location=”Japan”});
    l1.Add(new Students{Name=”Joseph”, Class=”9”, Location=”India”});
    return l1;

Add a label in the source code of the web page. The code is as shown below:

<html xmlns=”http://www.w3.org/1999/xhtml”>
 <head runat=”server”>
   <form is=”form1” runat=”server”>
    <asp:Label ID=”Label1” runat=”server” Text=”Names are:”></asp:Label>

The code for adding a LINQ query is as shown below:

public partial class _Default: System.Web.UI.Page
   protected void Page_Load(object sender, EventArgs e)
    List<Student> s1 = Students.GetItems();
    var studentinfo = from s in s1 select s.Name;
    foreach(var Name in studentinfo)
    Label1.Text+=String.Format(“{0}”<br/>”, Name);

The output is:

Like us on Facebook