LINQ
Still lots of folks don’t understand
what LINQ is doing. 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 he uses
ADO.Net. ADO.Net is serving as middle ware in application and provides complete
object oriented wrapper around the database SQL. Developing application in C#
and VB.Net so developer must have good knowledge of object oriented concept as
well as SQL, so it means developer must be familiar with both technologies to
develop an application. If here I can say SQL statements are become part of the
C# and VB.Net code so it’s not mistaken in form of LINQ. According to Anders
Hejlsberg the chief architect of C#.
“Microsoft original motivation
behind LINQ was to address the impedance mismatch between programming languages
and database.”
LINQ has a great power of querying on
any source of data, data source could be the collections of objects, database
or XML files. We can easily retrieve data from any object that implements the
IEnumerable<T> interface. Microsoft basically divides LINQ into three
areas and that are give below.
·
LINQ to Object {Queries performed
against the in-memory data}
·
LINQ to ADO.Net
o
LINQ to SQL (formerly DLinq) {Queries
performed against the relation database only Microsoft SQL Server Supported}
o
LINQ to DataSet {Supports queries by
using ADO.NET data sets and data tables}
o
LINQ to Entities {Microsoft ORM
solution}
·
LINQ to XML (formerly XLinq) { Queries
performed against the XML source}
I hope few above lines increase your
concrete knowledge about Microsoft LINQ and now we write some code snippet of
LINQ.
Linque
Linque to
sql
LINQ to SQL, a component of Visual Studio
Code Name "Orcas", provides a run-time infrastructure for managing
relational data as objects without losing the ability to query. It does this by
translating language-integrated queries into SQL for execution by the database,
and then translating the tabular results back into objects you define. Your
application is then free to manipulate the objects while LINQ to SQL stays in
the background tracking your changes automatically.
- LINQ to SQL is designed to be non-intrusive to your
application.
- It is possible to migrate current ADO.NET solutions to
LINQ to SQL in a piecemeal fashion (sharing the same connections and
transactions) since LINQ to SQL is simply another component in the
ADO.NET family. LINQ to SQL also has extensive support for stored
procedures, allowing reuse of the existing enterprise assets.
- LINQ to SQL applications are easy to get started.
- Objects linked to relational data can be defined just
like normal objects, only decorated with attributes to identify how
properties correspond to columns. Of course, it is not even necessary to
do this by hand. A design-time tool is provided to automate translating
pre-existing relational database schemas into object definitions for you.
The DataContext
is the main conduit by which you retrieve objects from the database and
resubmit changes. You use it in the same way that you would use an ADO.NET
Connection. In fact, the DataContext is initialized with a connection or
connection string you supply. The purpose of the DataContext is to
translate your requests for objects into SQL queries made against the database
and then assemble objects out of the results. The DataContext enables language-integrated
query by implementing the same operator pattern as the standard query
operators such as Where and Select.
Firstly add a linque to sql class and drag your table in to
that class than it will create own self it’s entitiy properties and classes
Than it will add datacontext keyword with the name of your
class.
// to select data
DataClasses1DataContext
ob = new DataClasses1DataContext();
private void button1_Click(object sender, EventArgs
e)
{
listBox1.Items.Clear();
var v = from m in ob.Employees
select m;
foreach(var v1 in v)
{
listBox1.Items.Add(v1.e_ID + " " + v1.e_Name + " "
+ v1.e_Family + " " + v1.e_PhoneNumber);
}
}
private void button2_Click(object sender, EventArgs
e)
{
}
//to insert a record in to the
database
Employee obj;
private void button3_Click(object sender, EventArgs
e)
{
obj = new Employee();
obj.e_ID = Convert.ToInt32(textBox1.Text);
obj.e_Name =
textBox2.Text;
obj.e_Family =
textBox3.Text;
obj.e_PhoneNumber =
textBox4.Text;
ob.Employees.InsertOnSubmit(obj);
ob.SubmitChanges();
}
/// to delete a record from a database
private void button4_Click(object sender, EventArgs
e)
{
var v = ob.Employees.Single(r => r.e_ID == int.Parse(textBox1.Text));
ob.Employees.DeleteOnSubmit(v);
ob.SubmitChanges();
}
//This is to update a record
private void button5_Click(object sender, EventArgs
e)
{
Employee ob1=ob.Employees.Single(r => r.e_ID ==
int.Parse(textBox1.Text));
ob1.e_Name =
textBox2.Text;
ob1.e_PhoneNumber =
textBox3.Text;
ob1.e_Family =
textBox4.Text;
ob.SubmitChanges();
}
// this is to access a first row of a selected records
private void button6_Click(object sender, EventArgs
e)
{
listBox1.Items.Clear();
var v=ob.Employees.First(r=>r.e_ID>503);
listBox1.Items.Add(v.e_ID + ""
+ v.e_Name + "
" + v.e_PhoneNumber + " " + v.e_Family);
}
first
var q = from o in db.Orders
where o.Products.ProductName.StartsWith("Asset") &&
o.PaymentApproved == true
select new { name = o.Contacts.FirstName + " " +
o.Contacts.LastName,
product = o.Products.ProductName,
version = o.Products.Version +
(o.Products.SubVersion * 0.1)
};
foreach(var x in q)
Console.WriteLine("{0} - {1} v{2}",
x.name, x.product, x.version)
second
var q = from call in db.CallLogs
join contact in db.Contacts on call.Number equals contact.Phone
select new {contact.FirstName, contact.LastName,
call.When, call.Duration};
foreach(var call in q)
Console.WriteLine("{0} - {1} {2} ({3}min)",
call.When.ToString("ddMMM HH:mm"),
call.FirstName.Trim(), call.LastName.Trim(), call.Duration);
third
Linque to
object
LINQ to Objects means that we can use LINQ to query objects in a
collection. We can access the in-memory data structures using LINQ. We can
query any type of object that implements the IEnumerable
interface or IEnumerable, which is of generic type. Lists, arrays, and dictionaries are
some collection objects that can be queried using LINQ
1.
Code Snippet
int[]
nums = new int[] {0,1,2};
var res = from a in nums where a < 3 orderby a select a; foreach(int i in res) Console.WriteLine(i);
Output:
0 1 2 |
All SQL Operates are available in LINQ
to Object like Sum Operator in the following code.
2.
Code Snippet
Output:
1 2 |
One thing that I want to share with you guys is LINQ to Object support querying against any object that inherits from IEnumerable (all .Net collection inherits from IEnumerable interface). LINQ to Object provided main types of Operator Type that are give below.
Operator Types
|
Operator Name
|
Aggregation
|
|
Conversion
|
|
Element
|
|
Equality
|
|
Generation
|
|
Grouping
|
|
Joining
|
|
Ordering
|
|
Partitioning
|
|
Quantifiers
|
|
Restriction
|
|
Selection
|
|
Set
|
|
Array
of integer
private void button1_Click(object
sender, EventArgs e)
{
int[] integers = { 1, 6, 2, 27, 10, 33, 12, 8, 14, 5
};
IEnumerable<int>
twoDigits = from numbers in integers
where numbers >= 10
select numbers;
foreach (var number in twoDigits)
{
listBox1.Items.Add(number);
}
}
First
four numbers from a number
private
void button2_Click(object
sender, EventArgs e)
{
int[] integers = { 1, 6, 2, 27, 10, 33, 12, 8, 14, 5
};
IEnumerable<int>
firstFourNumbers = integers.Take(4);
foreach (var number in firstFourNumbers)
{
listBox1.Items.Add(number);
}
}
Skip first four numbers
private void button3_Click(object
sender, EventArgs e)
{
int[] integers = { 1, 6, 2, 27, 10, 33, 12, 8, 14, 5
};
IEnumerable<int>
firstFourNumbers = integers.Skip(4);
foreach (var number in firstFourNumbers)
{
listBox1.Items.Add(number);
}
}
Take while a number found from a array
private void button4_Click(object
sender, EventArgs e)
{
int[] integers = { 1, 9, 5, 3, 7, 2, 11, 23, 50, 41,
6, 8 };
IEnumerable<int> takeWhileNumber =integers.TakeWhile(num =>
num.CompareTo(50) != 0);
foreach (int num in takeWhileNumber)
{
listBox1.Items.Add(num);
}
}
Skip while a number found from a array
private void button5_Click(object
sender, EventArgs e)
{
int[] integers = { 1, 9, 5, 3, 7, 2, 11, 23, 50, 41,
6, 8 };
IEnumerable<int>
takeWhileNumber = integers.SkipWhile(num => num.CompareTo(50) != 0);
foreach (int num in takeWhileNumber)
{
listBox1.Items.Add(num);
}
}
Reading from a string
Read upper character from a string
private void button6_Click(object
sender, EventArgs e)
{
string aString = "Satheesh
Kumar";
IEnumerable<char>
query = from ch in
aString
where Char.IsUpper(ch)
select ch;
foreach (char c in query)
{
listBox1.Items.Add(c);
}
}
Read lower character from a string
private
void button6_Click(object
sender, EventArgs e)
{
string aString = "Satheesh
Kumar";
IEnumerable<char>
query = from ch in
aString
where Char.IsLower(ch)
select ch;
foreach (char c in query)
{
listBox1.Items.Add(c);
}
}
using System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;
namespace
WindowsFormsApplication4
{
public
partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<Student> li;
private void button1_Click(object sender, EventArgs
e)
{
//Object Initializer-----------------------
//Student obj = new Student() { Rollno = 12, Name =
"Amit", City = "Noida" };
//MessageBox.Show(obj.Name);
// Collection Initializer----------------------------
li = new List<Student>(){
new
Student(){Rollno=23,Name="Amit",City="Noida"},
new Student(){Rollno=45,Name="mohit",City="Noida"},
new Student(){Rollno=2,Name="Rohit",City="Noida"},
new Student(){Rollno=12,Name="Akash",City="Noida"},
new Student(){Rollno=9,Name="Raj",City="Jiapur"},
new Student(){Rollno=21,Name="Rakesh",City="Delhi"},
new Student(){Rollno=67,Name="Alok",City="Noida"},
};
//foreach (Student s in li)
//{
//
MessageBox.Show(s.Name+", "+s.Rollno+", "+s.City);
//}
//Linq query using lambda
expression------------------------
//var ss = (from m in li where m.City == "Noida"
orderby m.Name descending select m).First(x => x.Rollno > 20);
// var ss = li.Where(x => x.City ==
"Noida").OrderByDescending(x => x.Name).First(x => x.Rollno
> 20);
//var ss = from m in li where m.City == "Noida"
orderby m.Name descending select m
// var v = new { Id = 1, City = "Noida" };
// var v = from m in li where m.City == "Noida"n
orderby m.Name descending select new { STudid = m.Rollno, Fname = m.Name };
//foreach (var s in v)
//{
//
listBox1.Items.Add(s.STudid+", "+s.Fname);
//}
//var ss = (from m in li group m by m.City into g select
g).Sum(xn;
//var ss = li.GroupBy(x => x.City);
//foreach (var s in ss)
//{
//
listBox1.Items.Add("Group by :" + s.Key + ",No. of items in
group " + s.Count());
//
listBox1.Items.Add("---------------------------------------------");
// foreach (var k
in s)
// {
//
listBox1.Items.Add(k.Rollno + "," + k.Name + ", " +
k.City);
// }
//}
//Example from
internet--------------------------------------for distinct()
string[] famousQuotes =
{
"Advertising
is legalized lying",
"Advertising
is the greatest art form of the twentieth century"
};
string[] cities = new
string[] { "Ducat",
"Noida", "Ducat",
"No", "Delhi"
};
var d= cities.Distinct();
var query = (from sentence in
famousQuotes from word in
sentence.Split(' ') select
word).Distinct();
}
}
}
To the good use of above operator
types I need samle patient class so here it
using System;
public class
Patient
{
// Fields
private string
_name;
private int
_age;
private string
_gender;
private string
_area;
// Properties
public string
PatientName
{
get { return
_name; }
set { _name = value;
}
}
public string
Area
{
get { return
_area; }
set { _area = value;
}
}
public String
Gender
{
get { return
_gender; }
set { _gender = value;
}
}
public int
Age
{
get { return
_age; }
set { _age = value;
}
}
}
|
Here is my code that intiliaze patients
object with following data.
List<Patient>
patients = new List<Patient> {
new Patient {
PatientName="Ali Khan", Age=20,
Gender="Male" , Area = "Gulshan"},
new Patient {
PatientName="Ahmed Siddiqui",
Age=25 ,Gender="Male", Area = "NorthKarachi" },
new Patient {
PatientName="Nida Ali", Age=20,
Gender="Female", Area = "NorthNazimabad"},
new Patient {
PatientName="Sana Khan", Age=18,
Gender="Female", Area = "NorthNazimabad"},
new Patient {
PatientName="Shahbaz Khan",
Age=19, Gender="Male", Area
= "Gulshan"},
new Patient {
PatientName="Noman Altaf",
Age=19, Gender="Male", Area
= "Gulshan"},
new Patient {
PatientName="Uzma Shah", Age=23,
Gender="Female", Area = "NorthKarachi"}};
Patient p = new
Patient();
p.Age =33; p.Gender = "male";
p.PatientName = "Hammad Ali";
p.Area = "Defence";
patients.Add(p);
|
This code snippet fetch those records whose gender is equal to “Male”.
gdView.DataSource = from pa in patients
where pa.Gender == "Male"
orderby pa.PatientName, pa.Gender, pa.Age
select pa;
gdView.DataBind();
|
The following code snippet uses the
selection operator type, which brings all those records whose age is more than 20 years.
var
mypatient = from pa in patients
where
pa.Age > 20
orderby pa.PatientName, pa.Gender, pa.Age
select pa;
foreach(var pp in
mypatient)
{
Debug.WriteLine(pp.PatientName + " "+ pp.Age + "
" +
pp.Gender);
}
|
The following code snippet uses
the grouping operator type that group patient data on the bases
area.
var
op = from pa in patients
group
pa by pa.Area into g
select new {area = g.Key, count = g.Count(), allpatient = g};
foreach(var g in
op)
{
Debug.WriteLine(g.count+ "," + g.area);
foreach(var l in
g.allpatient)
{
Debug.WriteLine("\t"+l.PatientName);
}
}
|
This code snippet determine the count
of those records, which lay in above 20 years.
int patientCount = (from pa in patients
where pa.Age > 20
orderby pa.PatientName, pa.Gender, pa.Age
select pa).Count();
|
All the above codes are few example of LINQ to Object technique of LINQ. In my up coming post you will see both LINQ to SQL and LINQ to XML code snippets
Linque to
xml
For
the purposes of this paper let's establish a simple XML contact list sample
that we can use throughout our discussion.
<contacts>
<contact>
<name>Patrick Hines</name>
<phone type="home">206-555-0144</phone>
<phone type="work">425-555-0145</phone>
<address>
<street1>123 Main St</street1>
<city>Mercer Island</city>
<state>WA</state>
<postal>68042</postal>
</address>
<netWorth>10</netWorth>
</contact>
<contact>
<name>Gretchen Rivas</name>
<phone type="mobile">206-555-0163</phone>
<address>
<street1>123 Main St</street1>
<city>Mercer Island</city>
<state>WA</state>
<postal>68042</postal>
</address>
<netWorth>11</netWorth>
</contact>
<contact>
<name>Scott MacDonald</name>
<phone type="home">925-555-0134</phone>
<phone type="mobile">425-555-0177</phone>
<address>
<street1>345 Stewart St</street1>
<city>Chatsworth</city>
<state>CA</state>
<postal>91746</postal>
</address>
<netWorth>500000</netWorth>
</contact>
</contacts>
private
void button1_Click(object
sender, EventArgs e)
{
XDocument xd=new XDocument
(
new XDeclaration("1.0","utf-8","no"),
new XComment("Document Created at "+DateTime.Now.ToString()),
new XElement("Employees",
new XElement("Employee",new
XElement("Id","1"),new
XElement("Name","Amit"),new
XElement("City","Noida")),
new XElement("Employee",new
XElement("Id","4"),new
XElement("Name","Aaa"),new
XElement("City","Delhi")),
new XElement("Employee",new
XElement("Id","5"),new
XElement("Name","bbb"),new
XElement("City","Jaipur")),
new XElement("Employee",new
XElement("Id","7"),new
XElement("Name","ccc"),new
XElement("City","Noida")),
new XElement("Employee",new
XElement("Id","8"),new
XElement("Name","ddd"),new
XElement("City","Noida"))
));
xd.Save("C:\\myfile.xml");
}
private void button2_Click(object sender, EventArgs
e)
{
XDocument doc= XDocument.Load("C:\\myfile.xml");
var v = from m in doc.Descendants("Employee")
where m.Element("City").Value
== "Noida" select m;
foreach(var a in v)
{
MessageBox.Show(a.Element("Name").Value.ToString());
}
}
To create a local variable
in the LINQ statement, you can use the let operator. You must use it before the select statement to hold the result. Here
is an example:
var fullNames = from empls
in employees
let FullName = empls.LastName + ", " + empls.FirstName select FullName;
foreach (var empl in fullNames)
Console.WriteLine(empl);
If you need a where condition but your let variable would be used only to hold
the final result, you can declare that let variable after the where statement. Here is an example:
var fullNames = from empls
in employees
where empls.LastName == "Mukoko" let FullName = empls.LastName + ", " + empls.FirstName
select FullName;
foreach (var empl in fullNames)
Console.WriteLine(empl);
You can create the let variable before the where statement and you would get the same
result:
var fullNames = from empls
in employees
let FullName = empls.LastName + ", " + empls.FirstName
where empls.LastName == "Mukoko" select FullName;
foreach (var empl in fullNames)
Console.WriteLine(empl);
To get the final result of
a query, you may want to combine a few fields or properties of the class. For
example, as we have seen so far, you may want to combine the last and the
first name of each result to create a full name. Besides, or instead of, the let operator, you can use the new operator to create such a combination.
To use the new operator, after the select keyword, type new followed by an opening "{"
and a closing curly "}" brackets. Inside the brackets, create an
expression as you see fit and assign it to a local variable in the curly
brackets. When accessing the result in your foreach loop, apply the period operator on
the foreach variable to access the new local variable(s). Here is an
example:
var fullNames = from empls
in employees
select new { FullName = empls.LastName + ", " + empls.FirstName };
foreach (var empl in fullNames)
Console.WriteLine(empl.FullName);
To make the statement
easier to read, you can span it on various lines:
var fullNames = from empls
in employees
select new {
FullName = empls.LastName + ", " + empls.FirstName
};
foreach (var empl in fullNames)
Console.WriteLine(empl.FullName);
One of the most valuable
features of the new operator is that it allows you to create
a selected query of fields of the members of the class. For example, you
cannot use a select statement to select more than one
member of the class that holds the value. On the other hand, you can create a new body in which you list the desired
members of the class, each member must be qualified using the period
operator. Here are examples:
var fullNames = from empls
in employees
select new
{
empls.EmployeeNumber, empls.LastName };
If you want one of the new fields to be a combination of the
members of the class, you must create a name for it and assign the expression
to it. Here is an example:
using System;
using System.Linq;
using System.Collections.Generic;
public class Exercise
{
static Employee[] employees;
public static int Main()
{
employees = new Employee[]
{
new Employee(971974, "Patricia", "Katts", 24.68M),
new Employee(208411, "Raymond", "Kouma", 20.15M),
new Employee(279374, "Hélène", "Mukoko", 15.55M),
new Employee(707912, "Bertrand", "Yamaguchi", 24.68M),
new Employee(971394, "Gertrude", "Monay", 20.55M)
};
var staffMembers = from empls
in employees
select new
{
empls.EmployeeNumber,
FullName = empls.LastName + ", " + empls.FirstName,
empls.HourlySalary
};
Console.WriteLine("+========+=====================+========+");
Console.WriteLine("| Empl # | Full Name | Salary |");
foreach (var staff in staffMembers)
{
Console.WriteLine("+--------+---------------------+--------+");
Console.WriteLine("| {0,6} | {1,-19} | {2,6} |", staff.EmployeeNumber,
staff.FullName, staff.HourlySalary);
}
Console.WriteLine("+========+=====================+========+");
Console.WriteLine();
return 0;
}
}
public class Employee
{
public int EmployeeNumber;
public string FirstName;
public string LastName;
public decimal HourlySalary;
public Employee(int number = 0,
string firstName = "John",
string lastName = "Doe",
decimal salary = 0M)
{
EmployeeNumber = number;
FirstName = firstName;
LastName = lastName;
HourlySalary = salary;
}
internal string GetFullName()
{
return LastName + ", " + FirstName;
}
}
This would produce:
In the same way, if you
want, in the new body, you can create a name for each
field and assign it the member of the class that holds the actual fields.
Here are examples:
public class Exercise
{
static Employee[] employees;
public static int Main()
{
employees = new Employee[]
{
new Employee(971974, "Patricia", "Katts", 24.68M),
new Employee(208411, "Raymond", "Kouma", 20.15M),
new Employee(279374, "Hélène", "Mukoko", 15.55M),
new Employee(707912, "Bertrand", "Yamaguchi", 24.68M),
new Employee(971394, "Gertrude", "Monay", 20.55M)
};
var staffMembers = from empls
in employees
select new
{
Number = empls.EmployeeNumber, FName = empls.FirstName, LName = empls.LastName, Wage = empls.HourlySalary };
Console.WriteLine("+========+============+===========+========+");
Console.WriteLine("| Empl # | First Name | Last Name | Salary |");
foreach (var staff in staffMembers)
{
Console.WriteLine("+--------+------------+-----------+--------+");
Console.WriteLine("| {0,6} | {1,-10} | {2,-9} | {3,6} |", staff.Number,
staff.FName, staff.LName, staff.Wage);
}
Console.WriteLine("+=======+============+===========+=========+");
Console.WriteLine();
return 0;
}
}
|
|||||||||||||||||||||
|
No comments:
Post a Comment