Tuesday 23 April 2013

LINQ Training - Hour 1

Written By:-Isha Malhotra(malhotra.isha3388@gmail.com)
if you find this article useful then leave your comment
LINQ-Hour 1

Language Integrated Query introduced in .net framework 3.5. LINQ integrated accessibility of data and query into language. LINQ makes easier to work with data.

Advantage of LINQ

Earlier when we connect to database, we used SQL queries as text like if we have to select any data from table then we write following queries:-

“select * from Table_name”

This query will be passed as text and if this query has some syntax error then it will be showed when this query will be executed means at runtime. But in LINQ at the time of compile time all syntax checked as it integrate query writing in our language(C# or Vb.net)

Query writing in LINQ

LINQ allows us to write query against all data whether it comes from array, database, XML etc.  This is the best feature of LINQ.

Before going deep into LINQ lets run some basic queries in LINQ using arrays and try to understand the syntax of LINQ


The namespace which is used for these queries is as follows:-

using System.Linq;

For Example:-

Let’s take the string array which contains the name of student as follows:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //declare the array
        string[] techaltum_student = new string[] { "isha", "avinash", "guddu", "neha sharma" };
       
        //quey using LINQ syntax
        IEnumerable<string> str_res = from res in techaltum_student
                                      select res;

        //access the element and print in the screen
        foreach (string final_res in str_res)
        {
            //show data with some spaces
            Response.Write(final_res+"   ");
       
        }
    }
}

The output of this code as follows:-



Figure1

Use of Where Clause in Query

We can also filter data using where clause. Some queries and answer as follows:-
 Show the names which length are 4 then we will write the query as follows:-

IEnumerable<string> str_res = from res in techaltum_student
                                      where res.Length==4
                                      select res;

Show the name which has the word “sh”

IEnumerable<string> str_res = from res in techaltum_student
                                      where res.Contains("sh")
                                      select res;

Use of order by in Query

If we want to sort the data then we use the order by in the query as follows:-

IEnumerable<string> str_res = from res in techaltum_student
                                      where res.Contains("sh")
                                      orderby res
                                      select res;
by default it will sort in ascending order.

If we want to sort in descending order then we will write the query as follows:-

IEnumerable<string> str_res = from res in techaltum_student
                                      where res.Contains("sh")
                                      orderby res descending
                                      select res;

Customization of output

We can also customize the output using query in LINQ.

For example

If you want to show the data in upper case then we customize the output as follows:-

IEnumerable<string> str_res = from res in techaltum_student
                                      where res.Contains("sh")
                                      orderby res descending
                                      select res.ToUpper();
Show data in Gridview

We can also show this data in gridview. The code is as follows:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //declare the array
        string[] techaltum_student = new string[] { "isha", "avinash", "guddu", "neha sharma" };
       
        //quey using LINQ syntax
        IEnumerable<string> str_res = from res in techaltum_student
                                      where res.Contains("sh")
                                      orderby res descending
                                      select res.ToUpper();


        GridView1.DataSource = str_res;
        GridView1.DataBind();
    }
}


Let’s take another example

Now implement LINQ on user defined data type. Create class and add some variable in it. I created the class name TechAltum and add some variable in it which is as follows:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for TechAltum
/// </summary>
public class TechAltum
{

    public int stu_id;
    public string stu_name;
    public string stu_course;
}

Now create list of type TechAltum data type and add some objects in it which is as follows and make query using LINQ which is as follow:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //creat list and add some object
        List<TechAltum> data = new List<TechAltum>() {
            new TechAltum{ stu_id=1, stu_name="Isha", stu_course="asp.net"},
            new TechAltum{ stu_id=2, stu_name="avinash", stu_course="Web Designing"},
            new TechAltum{ stu_id=3, stu_name="Rahul", stu_course="asp.net"},
            new TechAltum{ stu_id=4, stu_name="meena", stu_course="oracle"}

        };

        //as we know linq return in IEnumerable so i carried data in IEnumerable of type TechAltum
        IEnumerable<TechAltum> res = from final_Res in data
                              where final_Res.stu_id > 2 && final_Res.stu_course == "asp.net"
                              select final_Res;

      
        foreach (TechAltum ta in res)
        {

            Response.Write("Student Id=" + ta.stu_id + " Student Name=" + ta.stu_name + " Student Course=" + ta.stu_course);
       
        }

    }
}

The output of this code is as follows:-



Figure 2


Introducing new data Type VAR in LINQ
Var is data type in C# which holds the anonymous data. When you do not know the return type we can hold data in var. the declaration and definition of var type will be declare in the same line.
For example
Var x;
X=10;
That will be wrong syntax in case of var.
 Var x=10;
It will be the correct syntax.
Let’s perform the grouping the last example according to the course then we will use the code as follows with var data type:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //creat list and add some object
        List<TechAltum> data = new List<TechAltum>() {
            new TechAltum{ stu_id=1, stu_name="Isha", stu_course="asp.net"},
            new TechAltum{ stu_id=2, stu_name="avinash", stu_course="Web Designing"},
            new TechAltum{ stu_id=3, stu_name="Rahul", stu_course="asp.net"},
            new TechAltum{ stu_id=4, stu_name="meena", stu_course="oracle"}

        };

        //take the var data type
        var res = from final_Res in data
                  group final_Res by final_Res.stu_course;

      

        foreach (var course in res)
        {
            //preint the key on which we grouped data
            Response.Write("<html></br></br></html>"+course.Key + "<html></br></br></html>");

            foreach (var stu_data in course)
            {
                //show data
                Response.Write("Student Id=" + stu_data.stu_id + " Student Name=" + stu_data.stu_name + " Student Course=" + stu_data.stu_course+"<html></br></html>");
            }
        }

    }
}

The output of this code as follows:-



Figure 4

Hope you enjoyed the article

2 comments:

  1. Hi,
    Isha, I red your article. It is very good. I learn LINQ at so many site but your article taught me in the best way.

    Thanks

    ReplyDelete
  2. Awsome Article :)

    ReplyDelete