SlideShare a Scribd company logo
Damien Guard (BSc, MBCS)
http://damieng.com
damien@envytech.co.uk
Guernsey Software Developer Forum
http://developers.org.gg
Language Integrated
Query: An introduction
What is LINQ?
• Language Integrated Query
• Make query a part of the language
• Component of .NET Framework 3.5
• Now shipping with Visual Studio 2008
Query without LINQ
• Objects using loops and conditions
foreach(Customer c in customers)
if (c.Region == "UK") ...
• Databases using SQL
SELECT * FROM Customers WHERE
Region='UK'
• XML using XPath/XQuery
//Customers/Customer[@Region='UK']
ADO without LINQ
SqlConnection con = new SqlConnection(...);
con.Open();
SqlCommand cmd = new SqlCommand(
@"SELECT * FROM Customers
WHERE c.Region = @Region", con
);
cmd.Parameters.AddWithValue("@Region", "UK");
DataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
string name = dr.GetString(dr.GetOrdinal("Name"));
string phone = dr.GetString(dr.GetOrdinal("Phone"));
DateTime date = dr.GetDateTime(3);
}
dr.Close();
con.Close();
Query with LINQ
C#
var myCustomers = from c in customers
where c.Region == "UK"
select c;
VB.NET
Dim myCustomers = From c In customers _
Where c.Region = "UK" _
Select c
More LINQ queries
C#
var goodCusts = (from c in db.Customers
where c.PostCode.StartsWith("GY")
orderby c.Sales descending
select c).Skip(10).Take(10);
VB.NET
Dim goodCusts = (From c In db.Customers _
Where c.PostCode.StartsWith("GY") _
Order By c.Sales Descending _
Select c).Skip(1).Take(10)
Advantages
• Unified data access
Single syntax to learn and remember
• Strongly typed
Catch errors during compilation
• IntelliSense
Prompt for syntax and attributes
• Bindable result sets
Architecture
Others
C# VB.NET
.NET Language Integrated Query (LINQ)
LINQ
to SQL
LINQ
to Objects
LINQ
to XML
LINQ
to Datasets
LINQ
to Entities
LINQ data source providers
ADO.NET support for LINQ
LINQ to Objects
C#
int[] nums = new int[] {0,4,2,6,3,8,3,1};
double average = nums.Take(6).Average();
var above = from n in nums
where n > average
select n;
VB.NET
Dim nums() As Integer = {0,4,2,6,3,8,3,1}
Double average = nums.Take(6).Average()
Dim above = From n In nums _
Where n > average _
Select n
LINQ to Objects
• Query any IEnumerable<T> source
Includes arrays, List<T>, Dictionary...
• Many useful operators available
Sum, Max, Min, Distinct, Intersect, Union
• Expose your own data with
IEnumerable<T> or IQueryable<T>
• Create operators using extension methods
LINQ operators
Aggregate Conversion Ordering Partitioning Sets
Aggregate
Average
Count
Max
Min
Sum
Cast
OfType
ToArray
ToDictionar
y
ToList
ToLookup
ToSequenc
e
OrderBy
ThenBy
Descending
Reverse
Skip
SkipWhile
Take
TakeWhile
Concat
Distinct
Except
Intersect
Union
and many others
LINQ to SQL
• Object-relational mapping
Records become strongly-typed objects
• Data context is the controller mechanism
• Facilitates update, delete & insert
• Translates LINQ queries behind the scenes
• Type, parameter and injection safe
Database mapping
• VS 2008 designer or SQLMetal command
• Map tables & fields to classes & properties
• Generates partial classes with attributes
• Each record becomes an object
• Data context represents the database
• Utilise tables, views or stored procedures
Modifying objects
• Update
Set object properties
• Delete
context.Table.DeleteOnSubmit(object)
• Insert
context.Table.InsertOnSubmit(object)
• Commit changes back
context.SubmitChanges()
Transactional - all or nothing
Demo of LINQ to
SQL
Additional providers
• Relational data
NHibernate, MySQL, Oracle, PostgreSQL
• Web services
RDF, Flickr, Amazon, WebQueries
• Custom
LDAP, Google Desktop, SharePoint,
TerraServer maps
Future developments
• Blinq
Scaffold web UI for list/view/update pages
• PLINQ
Parallel query processing over many CPUs
• SyncLINQ & Continuous LINQ
Updated results via INotifyCollectionChanged
Limitations
LINQ
•Only defines query, not update or context
LINQ To SQL
•Mapping is set at compile time
•Can not mix mapped and unmapped
properties in a single query
•Microsoft SQL Server 2000, 2005 only
.NET features used
.NET Framework 2.0
• Partial classes (mapping)
.NET Framework 3.5
• Anonymous types (shaping)
• Extension methods (query operators)
• Type inference (var keyword)
• Lambda expressions (query syntax)
Alternatives for .NET
• NHibernate
• Castle MonoRail / ActiveRecord
• SubSonic
• Code generation tool + templates
CodeSmith, MyGeneration, LLBLGen/Pro +
NetTiers, DooDads, roll your own...
More information
• Official site - msdn.microsoft.com/linq/
• Tutorials - weblogs.asp.net/scottgu/
• Screencasts - tinyurl.com/yuscft
• This presentation & cheat sheet
damieng.com/blog/tag/linq
Questions & answers

More Related Content

Similar to LINQ-Introduction.ppt

What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?ukdpe
 
Linq in C#
Linq in C#Linq in C#
Linq in C#
Umar Farooq
 
Fast federated SQL with Apache Calcite
Fast federated SQL with Apache CalciteFast federated SQL with Apache Calcite
Fast federated SQL with Apache Calcite
Chris Baynes
 
Couchbas for dummies
Couchbas for dummiesCouchbas for dummies
Couchbas for dummies
Qureshi Tehmina
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
BizTalk360
 
Orms vs Micro-ORMs
Orms vs Micro-ORMsOrms vs Micro-ORMs
Orms vs Micro-ORMs
David Paquette
 
Understanding LINQ in C#
Understanding LINQ in C# Understanding LINQ in C#
Understanding LINQ in C#
MD. Shohag Mia
 
What's New in .Net 4.5
What's New in .Net 4.5What's New in .Net 4.5
What's New in .Net 4.5
Malam Team
 
El camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - IntroductionEl camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - Introduction
Plain Concepts
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Services
ukdpe
 
ASP.NET Lecture 4
ASP.NET Lecture 4ASP.NET Lecture 4
ASP.NET Lecture 4
Julie Iskander
 
Cloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure toolsCloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure tools
Pushkar Chivate
 
Link quries
Link quriesLink quries
Link quries
ulfat mushtaq
 
Access Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsAccess Data from XPages with the Relational Controls
Access Data from XPages with the Relational Controls
Teamstudio
 
Sql Summit Clr, Service Broker And Xml
Sql Summit   Clr, Service Broker And XmlSql Summit   Clr, Service Broker And Xml
Sql Summit Clr, Service Broker And Xml
David Truxall
 
Google cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache FlinkGoogle cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache Flink
Iván Fernández Perea
 
Surviving UI Automation Armageddon with BELLATRIX.pptx
Surviving UI Automation Armageddon with BELLATRIX.pptxSurviving UI Automation Armageddon with BELLATRIX.pptx
Surviving UI Automation Armageddon with BELLATRIX.pptx
NikolayAvramov4
 
SparkSQL: A Compiler from Queries to RDDs
SparkSQL: A Compiler from Queries to RDDsSparkSQL: A Compiler from Queries to RDDs
SparkSQL: A Compiler from Queries to RDDs
Databricks
 
Кирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, CiklumКирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, Ciklum
Alina Vilk
 
04 data accesstechnologies
04 data accesstechnologies04 data accesstechnologies
04 data accesstechnologiesBat Programmer
 

Similar to LINQ-Introduction.ppt (20)

What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?
 
Linq in C#
Linq in C#Linq in C#
Linq in C#
 
Fast federated SQL with Apache Calcite
Fast federated SQL with Apache CalciteFast federated SQL with Apache Calcite
Fast federated SQL with Apache Calcite
 
Couchbas for dummies
Couchbas for dummiesCouchbas for dummies
Couchbas for dummies
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
 
Orms vs Micro-ORMs
Orms vs Micro-ORMsOrms vs Micro-ORMs
Orms vs Micro-ORMs
 
Understanding LINQ in C#
Understanding LINQ in C# Understanding LINQ in C#
Understanding LINQ in C#
 
What's New in .Net 4.5
What's New in .Net 4.5What's New in .Net 4.5
What's New in .Net 4.5
 
El camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - IntroductionEl camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - Introduction
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Services
 
ASP.NET Lecture 4
ASP.NET Lecture 4ASP.NET Lecture 4
ASP.NET Lecture 4
 
Cloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure toolsCloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure tools
 
Link quries
Link quriesLink quries
Link quries
 
Access Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsAccess Data from XPages with the Relational Controls
Access Data from XPages with the Relational Controls
 
Sql Summit Clr, Service Broker And Xml
Sql Summit   Clr, Service Broker And XmlSql Summit   Clr, Service Broker And Xml
Sql Summit Clr, Service Broker And Xml
 
Google cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache FlinkGoogle cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache Flink
 
Surviving UI Automation Armageddon with BELLATRIX.pptx
Surviving UI Automation Armageddon with BELLATRIX.pptxSurviving UI Automation Armageddon with BELLATRIX.pptx
Surviving UI Automation Armageddon with BELLATRIX.pptx
 
SparkSQL: A Compiler from Queries to RDDs
SparkSQL: A Compiler from Queries to RDDsSparkSQL: A Compiler from Queries to RDDs
SparkSQL: A Compiler from Queries to RDDs
 
Кирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, CiklumКирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, Ciklum
 
04 data accesstechnologies
04 data accesstechnologies04 data accesstechnologies
04 data accesstechnologies
 

Recently uploaded

Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 

Recently uploaded (20)

Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 

LINQ-Introduction.ppt

  • 1. Damien Guard (BSc, MBCS) http://damieng.com damien@envytech.co.uk Guernsey Software Developer Forum http://developers.org.gg Language Integrated Query: An introduction
  • 2. What is LINQ? • Language Integrated Query • Make query a part of the language • Component of .NET Framework 3.5 • Now shipping with Visual Studio 2008
  • 3. Query without LINQ • Objects using loops and conditions foreach(Customer c in customers) if (c.Region == "UK") ... • Databases using SQL SELECT * FROM Customers WHERE Region='UK' • XML using XPath/XQuery //Customers/Customer[@Region='UK']
  • 4. ADO without LINQ SqlConnection con = new SqlConnection(...); con.Open(); SqlCommand cmd = new SqlCommand( @"SELECT * FROM Customers WHERE c.Region = @Region", con ); cmd.Parameters.AddWithValue("@Region", "UK"); DataReader dr = cmd.ExecuteReader(); while (dr.Read()) { string name = dr.GetString(dr.GetOrdinal("Name")); string phone = dr.GetString(dr.GetOrdinal("Phone")); DateTime date = dr.GetDateTime(3); } dr.Close(); con.Close();
  • 5. Query with LINQ C# var myCustomers = from c in customers where c.Region == "UK" select c; VB.NET Dim myCustomers = From c In customers _ Where c.Region = "UK" _ Select c
  • 6. More LINQ queries C# var goodCusts = (from c in db.Customers where c.PostCode.StartsWith("GY") orderby c.Sales descending select c).Skip(10).Take(10); VB.NET Dim goodCusts = (From c In db.Customers _ Where c.PostCode.StartsWith("GY") _ Order By c.Sales Descending _ Select c).Skip(1).Take(10)
  • 7. Advantages • Unified data access Single syntax to learn and remember • Strongly typed Catch errors during compilation • IntelliSense Prompt for syntax and attributes • Bindable result sets
  • 8. Architecture Others C# VB.NET .NET Language Integrated Query (LINQ) LINQ to SQL LINQ to Objects LINQ to XML LINQ to Datasets LINQ to Entities LINQ data source providers ADO.NET support for LINQ
  • 9. LINQ to Objects C# int[] nums = new int[] {0,4,2,6,3,8,3,1}; double average = nums.Take(6).Average(); var above = from n in nums where n > average select n; VB.NET Dim nums() As Integer = {0,4,2,6,3,8,3,1} Double average = nums.Take(6).Average() Dim above = From n In nums _ Where n > average _ Select n
  • 10. LINQ to Objects • Query any IEnumerable<T> source Includes arrays, List<T>, Dictionary... • Many useful operators available Sum, Max, Min, Distinct, Intersect, Union • Expose your own data with IEnumerable<T> or IQueryable<T> • Create operators using extension methods
  • 11. LINQ operators Aggregate Conversion Ordering Partitioning Sets Aggregate Average Count Max Min Sum Cast OfType ToArray ToDictionar y ToList ToLookup ToSequenc e OrderBy ThenBy Descending Reverse Skip SkipWhile Take TakeWhile Concat Distinct Except Intersect Union and many others
  • 12. LINQ to SQL • Object-relational mapping Records become strongly-typed objects • Data context is the controller mechanism • Facilitates update, delete & insert • Translates LINQ queries behind the scenes • Type, parameter and injection safe
  • 13. Database mapping • VS 2008 designer or SQLMetal command • Map tables & fields to classes & properties • Generates partial classes with attributes • Each record becomes an object • Data context represents the database • Utilise tables, views or stored procedures
  • 14. Modifying objects • Update Set object properties • Delete context.Table.DeleteOnSubmit(object) • Insert context.Table.InsertOnSubmit(object) • Commit changes back context.SubmitChanges() Transactional - all or nothing
  • 15. Demo of LINQ to SQL
  • 16. Additional providers • Relational data NHibernate, MySQL, Oracle, PostgreSQL • Web services RDF, Flickr, Amazon, WebQueries • Custom LDAP, Google Desktop, SharePoint, TerraServer maps
  • 17. Future developments • Blinq Scaffold web UI for list/view/update pages • PLINQ Parallel query processing over many CPUs • SyncLINQ & Continuous LINQ Updated results via INotifyCollectionChanged
  • 18. Limitations LINQ •Only defines query, not update or context LINQ To SQL •Mapping is set at compile time •Can not mix mapped and unmapped properties in a single query •Microsoft SQL Server 2000, 2005 only
  • 19. .NET features used .NET Framework 2.0 • Partial classes (mapping) .NET Framework 3.5 • Anonymous types (shaping) • Extension methods (query operators) • Type inference (var keyword) • Lambda expressions (query syntax)
  • 20. Alternatives for .NET • NHibernate • Castle MonoRail / ActiveRecord • SubSonic • Code generation tool + templates CodeSmith, MyGeneration, LLBLGen/Pro + NetTiers, DooDads, roll your own...
  • 21. More information • Official site - msdn.microsoft.com/linq/ • Tutorials - weblogs.asp.net/scottgu/ • Screencasts - tinyurl.com/yuscft • This presentation & cheat sheet damieng.com/blog/tag/linq