LINQ (Language Integrated Query) : It Is An Acronym For Language Integrated Query Which Was Released As A A Language

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

LINQ(Language Integrated Query)

Language Integrated Query is a Microsoft .NET Framework component

It is an acronym for language Integrated query which was released as a a


part of .net framework 3.5.It make possible to query data in .NET supported
language.

Basically LINQ address the current database development model in the context of
Object Oriented Programming Model. If some one wants to develop database
application on .Net platform the very simple approach we uses ADO.Net. ADO.Net is
serving as middle ware in application and provides complete object oriented wrapper
around the database SQL.So developer must have good knowledge of object oriented
concept as well as SQL to develop an application. But incase of Linq SQL statements are
become part of the C# and VB.Net code so there are less chance of mistake.

LINQ Architecture
Advantages of LINQ

 LINQ can be used for querying multiple data sources such as relational data and
XML data.

LINQ is declarative, it is very easy to understand and maintain.

 LINQ is extensible so new types of data sources can be made querable.

Var keyword

Var is new data type that has been introduced in 3.5 .Var request a variant DT,
In linq the actual Datatype is set at compile time.

Linq Simple Example

Linq to objects

Place a buuton

protected void Button1_Click(object sender, EventArgs e)

string[] names = new string[] { "rose", "pinky",


"nithya" };
var name = from i in names select i;//( In linq the actual
Datatype is set at compile time)

foreach (string a in name)

Response.Write(a);

Response.Write("<br>");

Output

protected void Button2_Click(object sender, EventArgs e)

int[] value = new[] { 3, 6, 8, 1 };

var output = from i in value where i < 8 orderby i


select i ;

foreach(int j in output)

{
Response.Write(j.ToString()+"<br>");

//Response.Write(a);

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

Lamda Expression

In Lamda expression the ‘=>’ is used to separate input variable on the left and
the body of the expression on the right .

Button_Click()

String [] names=new String [] {“a”,”b”};

Var name=names.Select(i=>i);

//(Same as ,var name = from i in names select i;)

Foreach(string a in name)

Response.write(a);

}
Linq to string

string input = "linq to string example";


var wordsorderbylength = from str in input.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries)
orderby str.Length select str

//select new { WordsOrderByLength = str };


GridView1.DataSource = wordsorderbylength;
GridView1.DataBind();

protected void Button2_Click(object sender, EventArgs e)


{
string input1 = "hi Hellow HI world hellow world world hi hi";
var wordsuinque = from str in input1.ToLowerInvariant().Split().Distinct() select
str
// select new { DistinctWords = str };
GridView2.DataSource = wordsuinque;
GridView2.DataBind();
}

LINQ to Array
Start with J
protected void Button1_Click(object sender, EventArgs e)
{
string[] ary = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec" };
var res = from months in ary
where months.StartsWith("J") select months
// select new { MonthStartWith_J = months };
GridView1.DataSource = res;
GridView1.DataBind();
}

2.Length Greater than 4

protected void Button2_Click(object sender, EventArgs e)


{
//string[] ary2 = new string[] { "Ravi", "Ramana", "Brod", "Wess", "Vinay",
"Smith", "Williams" };
//var names = from name in ary2
// where name.Length > 4
// select name;

//GridView2.DataSource = names;
//GridView2.DataBind();
//or

string[] ary2 = new string[] { "Ravi", "Ramana", "Brod", "Wess", "Vinay",


"Smith", "Williams" };
var names = from name in ary2
where name.Length > 4 select name;
// select new { NameMoreThan4Digits = name };
GridView2.DataSource = names;
GridView2.DataBind();

LINQ TO INTARRAY

Print 5 values in accending order’

protected void Button1_Click(object sender, EventArgs e)


{
//int[] ary1 = new int[] { 10, 27, 35, 40, 50, 11, 23, 25, 39, 22, 36 };

//var maxvalues = (from values in ary1 //int in an optional


// orderby (int)values descending
// select new { Max3Values = values }).Take(3);
//GridView1.DataSource = maxvalues;
//GridView1.DataBind();

int[] ary1 = new int[] { 10, 27, 35, 40, 50, 11, 23, 25, 39, 22, 36 };

var maxvalues = (from values in ary1


orderby values descending
select values).Take(5);
GridView1.DataSource = maxvalues;
GridView1.DataBind();
}
Print value between 20 and 35

protected void Button2_Click(object sender, EventArgs e)


{
int[] ary2 = new int[] { 10, 27, 35, 40, 50, 11, 23, 25, 39, 22, 36 };
var res = from values in ary2
where (int)values >= 20 && (int)values <= 35
orderby (int)values select value
// select new { ValuesBetween20_35 = values };
GridView2.DataSource = res;
GridView2.DataBind();
}

Print Even Numbers

protected void Button3_Click(object sender, EventArgs e)


{
int[] ary3 = new int[] { 10, 27, 35, 40, 50, 11, 23, 25, 39, 22, 36 };
var evennumbers = from values in ary3
where (int)values % 2 == 0
orderby (int)values select values;
//select new { EvenNumbers = values };
GridView3.DataSource = evennumbers;
GridView3.DataBind();
}

LINQ TO LIST

public partial class LintoList : System.Web.UI.Page


{

public class Products


{
private string _productName;
private string _category;
private decimal _price;

public string ProductName


{
get { return _productName; }
set { _productName = value; }
}

public string Category


{
get { return _category; }
set { _category = value; }
}

public decimal Price


{
get { return _price; }
set { _price = value; }
}

}
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
List<Products> listProducts = new List<Products>();
listProducts.Add(new Products { ProductName = "Mobile", Category = "Electronics",
Price = 6000 });
listProducts.Add(new Products { ProductName = "Fridge", Category = "Electronics",
Price = 12000 });
listProducts.Add(new Products { ProductName = "Chair", Category = "HomeNeeds",
Price = 1000 });
listProducts.Add(new Products { ProductName = "Table", Category = "HomeNeeds",
Price = 6000 });
listProducts.Add(new Products { ProductName = "T-Shirt", Category = "Clothes",
Price = 1500 });
listProducts.Add(new Products { ProductName = "Jeans", Category = "Clothes",
Price = 3500 });

var proudcts = from products in listProducts


where products.Price > 5000 && products.Price < 10000
orderby products.Price;

select new { products.ProductName, products.Category,


products.Price };
GridView1.DataSource = proudcts;
GridView1.DataBind();

Linq To SQL

Right click soln explorer->addnewitem->linq to sql class

Drag tables in it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class detailsv : System.Web.UI.Page


{
public int a;
public void viewstudent()
{
DataClassesDataContext ds = new DataClassesDataContext();
var qry = from res in ds.studdetails select res;
GridView1.DataSource = qry;
GridView1.DataBind();
}

protected void Page_Load(object sender, EventArgs e)


{
if(!IsPostBack)
{
viewstudent();
}
}
protected void Button1_Click(object sender, EventArgs e)
{

DataClassesDataContext ds = new DataClassesDataContext();


studdetail d = new studdetail();
d.name = TextBox1.Text;
d.address = TextBox2.Text;
ds.studdetails.InsertOnSubmit(d);

ds.SubmitChanges();
viewstudent();

}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
// GridView1.EditIndex = -1;
//GridView1.EditIndex = -1;
//Label1.Text = GridView1.DataKeys[e.NewEditIndex].Value.ToString();
// a = int.Parse(Label1.Text);

//DataClassesDataContext ds = new DataClassesDataContext();


//var qry = (from res in ds.studdetails where res.sid == a select res).First();
//TextBox1.Text = qry.name;
//TextBox2.Text = qry.address;
viewstudent();
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)


{
DataClassesDataContext ds = new DataClassesDataContext();

string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
// Response.Write(id);
string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
// Response.Write(name);
//string age = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string address = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
// Response.Write(address);

studdetail d = (from res in ds.studdetails where (res.sid == int.Parse(id))


select res).First();
d.sid = int.Parse(id);
d.name = name;
// Response.Write(d.name);
d.address = address;
ds.SubmitChanges();
GridView1.EditIndex = -1;
viewstudent();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
DataClassesDataContext ds = new DataClassesDataContext();
// var qry = (from ss in ds.studentdetails where (ss.stid == int.Parse(id)) select
ss).SingleOrDefault();
var res1 = (from res in ds.studdetails where (res.sid == int.Parse(id)) select
res).First();
ds.studdetails.DeleteOnSubmit(res1);
ds.SubmitChanges();
viewstudent();

}
}

Display in Gridview

public partial class LINQTOSQL_sql : System.Web.UI.Page


{

roseDataContext r = new roseDataContext();


protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
var employees = from emps in r.employeenews
select new
{
emps.name,
emps.salary

};
GridView1.DataSource = employees;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{

var employees = from emps in r.employeenews


where Convert.ToInt32( emps.salary) > 5000
orderby emps.name

select new
{
emps.eid,
emps.name,
emps.salary
};
GridView2.DataSource = employees;
GridView2.DataBind();
}
}

Join linq to sql


public partial class LINQTOSQL_join : System.Web.UI.Page
{
roseDataContext r = new roseDataContext();
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
var employees = from emps in r.employeenews
join depts in r.departments on emps.did equals depts.did
select new
{
emps.name,

emps.salary,
depts.deptname
};
GridView1.DataSource = employees;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
var employees = from emps in r.employeenews
join depts in r.departments on emps.did equals depts.did
select new
{
emps.name,

emps.salary,
depts.deptname
};
GridView1.DataSource = employees;
GridView1.DataBind();

}
}

Assignment

Where ,Group By

Like Operator
public partial class LINQTOSQL_like : System.Web.UI.Page
{
roseDataContext r = new roseDataContext();
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
//MyDBDataContext sqlObj = new MyDBDataContext();
var employees = from emps in r.employeenews
where emps.name.Contains("j")
select new
{

emps.name,
emps.salary
};
GridView1.DataSource = employees;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
var employees = from emps in r.employeenews
where emps.name.StartsWith("j")//.EndsWith(“r”)
select new
{

emps.name,
emps.salary
};
GridView1.DataSource = employees;
GridView1.DataBind();
}
}
Insert,Update in a Table
public partial class LINQTOSQL_Inserttable : System.Web.UI.Page
{
roseDataContext r = new roseDataContext();
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
employeenew em = new employeenew();
em.name = "rose";
em.did = 2;
em.salary = "40000";
r.employeenews.InsertOnSubmit(em);
r.SubmitChanges();

}
protected void Button2_Click(object sender, EventArgs e)
{
roseDataContext r = new roseDataContext();
employeenew em =r.employeenews.Single(x => x.eid== 2);
em.name = "Sreeja S Nair";
r.SubmitChanges();
}
}

Single() / SingleOrDefault() First () / FirstOrDefault()

Single() - There is exactly 1 result, an exception is First() - There is at least one result, an exception is
thrown if no result is returned or more than one thrown if no result is returned.
result.
FirstOrDefault() - Same as First(), but not thrown
SingleOrDefault() – Same as Single(), but it can any exception or return null when there is no result.
handle the null value.

Single() asserts that one and only one element First() simply gives you the first one.
exists in the sequence.

When to use When to use


Use Single / SingleOrDefault() when you sure there Developer may use First () / FirstOrDefault()
is only one record present in database or you can anywhere, when they required single value from
say if you querying on database with help of collection or database.
primary key of table.

Single() or SingleOrDefault() will generate a regular The First() or FirstOrDefault() method will generate
TSQL like "SELECT ...". the TSQL statment like "SELECT TOP 1..."

In the case of First / FirstOrDefault, only one row is retrieved from the database so it performs slightly
better than single / SingleOrDefault. such a small difference is hardly noticeable but when table contain
large number of column and row, at this time performance is noticeable.

You might also like