SlideShare uma empresa Scribd logo
1 de 33
LINQ Language-Integrated Query
Table of content ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Table of content ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What is LINQ ,[object Object],[object Object]
Language Features that Enable LINQ ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Flavors of LINQ ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
LINQ Architecture
LINQ to Objects
LINQ to Objects The term "LINQ to Objects" refers to the use of LINQ queries with any  IEnumerable  or IEnumerable(Of  T)  collection directly, without the use of an intermediate LINQ provider or API such as  LINQ to SQL  or  LINQ to XML . You can use LINQ to query any enumerable collections such as List(Of  T) ,  Array , or  Dictionary(Of   TKey ,  TValue ) . The collection may be user-defined or may be returned by a .NET Framework API. In a basic sense, LINQ to Objects represents a new approach to collections. In the old way, you had to write complex foreach loops that specified how to retrieve data from a collection. In the LINQ approach, you write declarative code that describes what you want to retrieve. In addition, LINQ queries offer three main advantages over traditional foreach loops: ,[object Object],[object Object],[object Object]
Language   Features That Support LINQ Query Expressions   Query expressions in Visual Basic 2008 can be expressed in a declarative syntax similar to that of SQL or XQuery. At compile time, query syntax is converted into method calls to a LINQ provider's implementation of the standard query operator extension methods. Applications control which standard query operators are in scope by specifying the appropriate namespace with an Imports statement. Syntax for a Visual Basic query expression looks like this: Dim londonCusts = From cust In customers _    Where cust.City = "London" _    Order By cust.Name Ascending _    Select cust.Name, cust.Phone
LINQ Query Syntax Shaping the output select <expression> Projection Aggregate the source items count([<expression>]), sum(<expression>), min(<expression>), max (<expression>), avg(<expression>) Aggregate Control the ordering of the results order by <expression>, <expression> [Ascending | Descending] Order Expression specifying the selection Criteria where <expression>, distinct Filter Information source providing a set of item (s) from <item> in <data source> Source Using type inference to assign the resulting value(s) var <variable> = Destination
Language Features That Support LINQ Implicitly Typed Variables   Instead of explicitly specifying a type when you declare and initialize a variable, you can now enable the compiler to infer and assign the type, as shown in the following example. This is referred to as local type inference.  ' The variable number will be typed as an integer.   Dim aNumber = 5  ' The variable name will be typed as a String .  Dim aName = &quot;Virginia&quot;
Language   Features That Support LINQ Object Initializers  Object initializers are used in query expressions when you have to create an anonymous type to hold the results of a query. They also can be used to initialize objects of named types outside of queries. By using an object initializer, you can initialize an object in a single line without explicitly calling a constructor. Assuming that you have a class named Customer that has public Name and Phone properties, along with other properties, an object initializer can be used in this manner: Dim aCust As Customer = New Customer With {.Name =  &quot;Mike&quot;, _ .Phone = &quot;555-0212&quot;}
Language Features That Support LINQ Anonymous Types  Anonymous types provide a convenient way to temporarily group a set of properties into an element that you want to include in a query result. This enables you to choose any combination of available fields in the query, in any order, without defining a named data type for the element.  An anonymous type is constructed dynamically by the compiler. The name of the type is assigned by the compiler, and it might change with each new compilation. Therefore, the name cannot be used directly. Anonymous types are initialized in the following way: ' Outside a query.  Dim product = New With {.Name = &quot;paperclips&quot;, .Price = 1.29}   ' Inside a query.  ' You can use the existing member names of the selected fields, as was  ' shown previously in the Query Expressions section of this topic.  Dim londonCusts1 = From cust In customers_   Where cust.City = &quot;London“  _ Select cust.Name, cust.Phone  ' Or you can specify new names for the selected fields.  Dim londonCusts2 = From cust In customers _  Where cust.City = &quot;London&quot; _  Select CustomerName = cust.Name, _  CustomerPhone = cust.Phone
Language Features That Support LINQ Extension Methods   Extension methods enable you to add methods to a data type or interface from outside the definition. This feature enables you to, in effect, add new methods to an existing type without actually modifying the type. The standard query operators are themselves a set of extension methods that provide LINQ query functionality for any type that implements  IEnumerable(Of  T) . Other extensions to  IEnumerable(Of  T)  include  Count ,  Union , and  Intersect . ' Import System.Runtime.CompilerServices to use the Extension attribute.  <Extension()> _  Public Sub Print(ByVal str As String)  Console.WriteLine(str)  End Sub  Dim greeting As String = &quot;Hello&quot;  greeting.Print()  The following extension method adds a print method to the  String  class. The method is called like an ordinary instance method of  String :
Language Features That Support LINQ Lambda Expressions   A lambda expression is a function without a name that calculates and returns a single value. Unlike named functions, a lambda expression can be defined and executed at the same time. The following example displays 4. Console.WriteLine((Function(num As Integer) num + 1)(3))  You can assign the lambda expression definition to a variable name and then use the name to call the function. The following example also displays 4. Dim add1 = Function(num As Integer) num + 1 Console.WriteLine(add1(3))  In LINQ, lambda expressions underlie many of the standard query operators. The compiler creates lambda expressions to capture the calculations that are defined in fundamental query methods such as Where, Select, Order By, Take While, and others. For example, the following code defines a query that returns all senior students from a list of students. Dim seniorsQuery = From stdnt In students Where stdnt.Year = &quot;Senior&quot;  Select stdnt  The query definition is compiled into code that is similar to the following example, which uses two lambda expressions to specify the arguments for Where and Select. Dim seniorsQuery2 = students Where(Function(st) st.Year = &quot;Senior&quot;) Select(Function(s) s)
More On Queries Like normal SQL queries we can do the following operations by using LINQ expressions Describes the Skip clause, which bypasses a specified number of elements in a collection and then returns the remaining elements. Skip Clause Describes the Select clause, which declares a set of range variables for a query Select Clause Describes the Order By clause, which specifies the sort order for columns in a query. Order By Clause Describes the Let clause, which computes a value and assigns it to a new variable in the query. Let Clause Describes the Join clause, which combines two collections into a single collection. Join Clause Describes the Group Join clause, which combines two collections into a single hierarchical collection. Group Join Clause Describes the Group By clause, which groups the elements of a query result and can be used to apply aggregate functions to each group. Group By Clause Describes the From clause, which specifies a collection and a range variable for a query. From Clause Describes the Distinct clause, which restricts the values of the current range variable to eliminate duplicate values in query results. Distinct Clause Describes the Aggregate clause, which applies one or more aggregate functions to a collection Aggregate Clause Descriptions Clause Name
More On Queries Like normal SQL queries we can do the following operations by using LINQ expressions Describes the Skip While clause, which bypasses elements in a collection as long as a specified condition is true and then returns the remaining elements. Skip While Clause Describes the Where clause, which specifies a filtering condition for a query. Where Clause Describes the Take While clause, which includes elements in a collection as long as a specified condition is true and bypasses the remaining elements. Take While Describes the Take clause, which returns a specified number of contiguous elements from the start of a Collection Take  Descriptions Clause Name
Queries – Order By Clause   Specifies the sort order for a query result. Syntax: Order By orderExp1 [ Ascending | Descending ] [, orderExp2 [...] ] Example The following query expression uses a From clause to declare a range variable book for the books collection. The Order By clause sorts the query result by price in ascending order (the default). Books with the same price are sorted by title in ascending order. The Select clause selects only the Title property as the value returned by the query. Dim titlesAscendingPrice = From book In books Order By book.Price, book.Title Select book.Title, book.Price The following query expression uses the Order By clause to sort the query result by price in descending order. Books with the same price are sorted by title in ascending order. Dim titlesDescendingPrice = From book In books Order By book.Price Descending, book.Title _   Select book.Title, book.Price Dim bookOrders = From book In books Select book.Title, book.Price, book.PublishDate, book.Author _    Order By Author, Title, Price
Queries – Distinct By Clause   Restricts the values of the current range variable to eliminate duplicate values in subsequent query clauses. You can use the Distinct clause to return a list of unique items. The Distinct clause causes the query to ignore duplicate query results. The Distinct clause applies to duplicate values for all return fields specified by the Select clause. If no Select clause is specified, the Distinct clause is applied to the range variable for the query identified in the From clause. If the range variable is not an immutable type, the query will only ignore a query result if all members of the type match an existing query result. Example The following query expression joins a list of customers and a list of customer orders. The Distinct clause is included to return a list of unique customer names and order dates. Dim customerOrders = From cust In customers, ord In orders _   Where cust.CustomerID = ord.CustomerID _ Select cust.CompanyName, ord.OrderDate Distinct
Queries – From Clause   Specifies one or more range variables and a collection to query.  Syntax: From element [ As type ] In collection [ _ ] [, element2 [ As type2 ] In collection2 [, ... ] ] Example: Dim customersForRegion = From cust In customers You can specify multiple From clauses in a query to identify multiple collections to be joined. When multiple collections are specified, they are iterated over independently, or you can join them if they are related. You can join collections implicitly by using the Select clause, or explicitly by using the Join or Group Join clauses. As an alternative, you can specify multiple range variables and collections in a single From clause, with each related range variable and collection separated from the others by a comma. The following code example shows both syntax options for the From clause.
Queries – From Clause  Continue  … ' Multiple From clauses in a query. Dim result = From var1 In collection1, var2 In collection2 ' Equivalent syntax with a single From clause. Dim result2 = From var1 In collection1 _   From var2 In collection2 The From clause defines the scope of a query, which is similar to the scope of a For loop. Therefore, each  element  range variable in the scope of a query must have a unique name. Because you can specify multiple From clauses for a query, subsequent From clauses can refer to range variables in the From clause, or they can refer to range variables in a previous From clause. For example, the following example shows a nested From clause where the collection in the second clause is based on a property of the range variable in the first clause. Dim allOrders = From cust In GetCustomerList() _   From ord In cust.Orders _   Select ord Dim customersForRegion = From cust In customers _   Where cust.Region = region
LINQ to Dataset
LINQ to Dataset
Queering Dataset Coverage  Areas ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Language-Integrated Query (LINQ) queries work on data sources that implement the  IEnumerable(Of  T)  interface or the IQueryable interface. The  DataTable  class does not implement either interface, so you must call the  AsEnumerable  method if you want to use the  DataTable  as a source in the From clause of a LINQ query.
Queering Dataset Single Table Queries The following example gets all the online orders from the SalesOrderHeader table and outputs the order ID, order date, and order number to the console.  ' Fill the DataSet. Dim ds As New DataSet() ds.Locale = CultureInfo.InvariantCulture ' See the FillDataSet method in the Loading Data Into a DataSet topic. FillDataSet(ds) Dim orders As DataTable = ds.Tables(&quot;SalesOrderHeader&quot;) Dim query =  From order In orders.AsEnumerable() _ Where order.Field(Of Boolean)(&quot;OnlineOrderFlag&quot;) = True _ Select New With { _ .SalesOrderID = order.Field(Of Integer)(&quot;SalesOrderID&quot;), _ .OrderDate = order.Field(Of DateTime)(&quot;OrderDate&quot;), _ .SalesOrderNumber = order.Field(Of String)(&quot;SalesOrderNumber&quot;) _ } For Each onlineOrder In query Console.Write(&quot;Order ID: &quot; & onlineOrder.SalesOrderID) Console.Write(&quot; Order date: &quot; & onlineOrder.OrderDate) Console.WriteLine(&quot; Order number: &quot; & onlineOrder.SalesOrderNumber) Next
Queering Dataset Accessing Values without using Field method Dim products As DataTable = ds.Tables(&quot;Product&quot;) Dim query = _ From product In products.AsEnumerable() _ Where product!Color IsNot DBNull.Value AndAlso product!Color = &quot;Red&quot; _ Select New With _ { _ .Name = product!Name, _ .ProductNumber = product!ProductNumber, _ .ListPrice = product!ListPrice _ } For Each product In query Console.WriteLine(&quot;Name: &quot; & product.Name) Console.WriteLine(&quot;Product number: &quot; & product.ProductNumber) Console.WriteLine(&quot;List price: $&quot; & product.ListPrice & vbNewLine) Next
Queering Dataset Accessing Values using Field method Dim products As DataTable = ds.Tables(&quot;Product&quot;) Dim query = _ From product In products.AsEnumerable() _ Where product.Field(Of String)(&quot;Color&quot;) = &quot;Red&quot; _ Select New With _ { _ .Name = product.Field(Of String)(&quot;Name&quot;), _ .ProductNumber = product.Field(Of String)(&quot;ProductNumber&quot;), _ .ListPrice = product.Field(Of Decimal)(&quot;ListPrice&quot;) _ } For Each product In query Console.WriteLine(&quot;Name: &quot; & product.Name) Console.WriteLine(&quot;Product number: &quot; & product.ProductNumber) Console.WriteLine(&quot;List price: $ &quot; & product.ListPrice & vbNewLine) Next
Queering Dataset Advantage of using Field method and SetField method The  Field  method provides access to the column values of a  DataRow  and the  SetField  sets column values in a  DataRow . Both the  Field  method and  SetField  method handle nullable types, so you do not have to explicitly check for null values as in the previous example. Both methods are generic methods, also, so you do not have to cast the return type.
Queering Dataset Cross-Table Queries The Language-Integrated Query (LINQ) framework provides two join operators,  Join  and  GroupJoin . These operators perform equi-joins: that is, joins that match two data sources only when their keys are equal. (By contrast, Transact-SQL supports join operators other than equals, such as the less than operator.)   In relational database terms,  Join  implements an inner join. An inner join is a type of join in which only those objects that have a match in the opposite data set are returned.  The  GroupJoin  operators have no direct equivalent in relational database terms; they implement a superset of inner joins and left outer joins. A left outer join is a join that returns each element of the first (left) collection, even if it has no correlated elements in the second collection.
Queering Dataset Cross-Table Queries Dim orders As DataTable = ds.Tables(&quot;SalesOrderHeader&quot;) Dim details As DataTable = ds.Tables(&quot;SalesOrderDetail&quot;) Dim query = _ From order In orders.AsEnumerable() _ Join detail In details.AsEnumerable() _ On order.Field(Of Integer)(&quot;SalesOrderID&quot;) Equals _ detail.Field(Of Integer)(&quot;SalesOrderID&quot;) _ Where order.Field(Of Boolean)(&quot;OnlineOrderFlag&quot;) = True And _ order.Field(Of DateTime)(&quot;OrderDate&quot;).Month = 8 _ Select New With _ { _ .SalesOrderID = order.Field(Of Integer)(&quot;SalesOrderID&quot;), _ .SalesOrderDetailID = detail.Field(Of Integer)(&quot;SalesOrderDetailID&quot;), _ .OrderDate = order.Field(Of DateTime)(&quot;OrderDate&quot;), _ .ProductID = detail.Field(Of Integer)(&quot;ProductID&quot;) _ } For Each order In query Console.WriteLine(order.SalesOrderID & vbTab & _ order.SalesOrderDetailID & vbTab & _ order.OrderDate & vbTab & _ order.ProductID) Next
Queering Dataset Querying Typed DataSets A typed DataSet is a class that derives from a DataSet. As such, it inherits all the methods, events, and properties of a DataSet. Additionally, a typed DataSet provides strongly typed methods, events, and properties. This means you can access tables and columns by name, instead of using collection-based methods. Aside from the improved readability of the code, a typed DataSet also allows the Visual Studio .NET code editor to automatically complete lines as you type.  Additionally, the strongly typed DataSet provides access to values as the correct type at compile time. With a strongly typed DataSet, type mismatch errors are caught when the code is compiled rather than at run time.  Typed DataSets LINQ to DataSet also supports querying over a typed  DataSet . With a typed  DataSet , you do not have to use the generic  Field  method or  SetField  method to access column data.  Property names are available at compile time because the type information is included in the  DataSet . LINQ to DataSet provides access to column values as the correct type, so that type mismatch errors are caught when the code is compiled instead of at run time.
Queering Dataset Querying Typed DataSets Dim orders = ds.Tables(&quot;SalesOrderHeader&quot;) Dim query = _ From o In orders _ Where o.OnlineOrderFlag = True _ Select New {SalesOrderID := o.SalesOrderID, _ OrderDate := o.OrderDate, _ SalesOrderNumber := o.SalesOrderNumber} For Each Dim onlineOrder In query Console.WriteLine(&quot;{0}{1:d}{2}&quot;, _ onlineOrder.SalesOrderID, _ onlineOrder.OrderDate, _ onlineOrder.SalesOrderNumber) Next

Mais conteúdo relacionado

Mais procurados

Description and Discovery of Type Adaptors for Web Services Workflow
Description and Discovery of Type Adaptors for Web Services WorkflowDescription and Discovery of Type Adaptors for Web Services Workflow
Description and Discovery of Type Adaptors for Web Services WorkflowMartin Szomszor
 
F# Type Providers in Depth
F# Type Providers in DepthF# Type Providers in Depth
F# Type Providers in DepthTomas Petricek
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: FundamentalsMahmoud Abdallah
 
c# usage,applications and advantages
c# usage,applications and advantages c# usage,applications and advantages
c# usage,applications and advantages mohamed drahem
 
tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...
tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...
tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...Anil Sharma
 
SessionTen_CaseStudies
SessionTen_CaseStudiesSessionTen_CaseStudies
SessionTen_CaseStudiesHellen Gakuruh
 
Implementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyImplementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyMartin Odersky
 
FireWatir - Web Application Testing Using Ruby and Firefox
FireWatir - Web Application Testing Using Ruby and FirefoxFireWatir - Web Application Testing Using Ruby and Firefox
FireWatir - Web Application Testing Using Ruby and Firefoxangrez
 
Web classification of Digital Libraries using GATE Machine Learning
Web classification of Digital Libraries using GATE Machine LearningWeb classification of Digital Libraries using GATE Machine Learning
Web classification of Digital Libraries using GATE Machine Learningsstose
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming conceptsandeshjadhav28
 
Resharper - Next Steps
Resharper - Next StepsResharper - Next Steps
Resharper - Next StepsTimmy Kokke
 
Semantic RDF based integration framework for heterogeneous XML data sources
Semantic RDF based integration framework for heterogeneous XML data sourcesSemantic RDF based integration framework for heterogeneous XML data sources
Semantic RDF based integration framework for heterogeneous XML data sourcesDeniz Kılınç
 

Mais procurados (20)

Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 
Description and Discovery of Type Adaptors for Web Services Workflow
Description and Discovery of Type Adaptors for Web Services WorkflowDescription and Discovery of Type Adaptors for Web Services Workflow
Description and Discovery of Type Adaptors for Web Services Workflow
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
I x scripting
I x scriptingI x scripting
I x scripting
 
F# Type Providers in Depth
F# Type Providers in DepthF# Type Providers in Depth
F# Type Providers in Depth
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: Fundamentals
 
c# usage,applications and advantages
c# usage,applications and advantages c# usage,applications and advantages
c# usage,applications and advantages
 
Basic
BasicBasic
Basic
 
tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...
tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...
tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...
 
SessionTen_CaseStudies
SessionTen_CaseStudiesSessionTen_CaseStudies
SessionTen_CaseStudies
 
Implementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyImplementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in Dotty
 
Hive
HiveHive
Hive
 
FireWatir - Web Application Testing Using Ruby and Firefox
FireWatir - Web Application Testing Using Ruby and FirefoxFireWatir - Web Application Testing Using Ruby and Firefox
FireWatir - Web Application Testing Using Ruby and Firefox
 
Web classification of Digital Libraries using GATE Machine Learning
Web classification of Digital Libraries using GATE Machine LearningWeb classification of Digital Libraries using GATE Machine Learning
Web classification of Digital Libraries using GATE Machine Learning
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
 
oracle-reports6i
oracle-reports6ioracle-reports6i
oracle-reports6i
 
d2k
d2kd2k
d2k
 
Resharper - Next Steps
Resharper - Next StepsResharper - Next Steps
Resharper - Next Steps
 
Semantic RDF based integration framework for heterogeneous XML data sources
Semantic RDF based integration framework for heterogeneous XML data sourcesSemantic RDF based integration framework for heterogeneous XML data sources
Semantic RDF based integration framework for heterogeneous XML data sources
 

Semelhante a Linq

C# advanced topics and future - C#5
C# advanced topics and future - C#5C# advanced topics and future - C#5
C# advanced topics and future - C#5Peter Gfader
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Featurestechfreak
 
Project_Report (BARC-Jerin)_final
Project_Report (BARC-Jerin)_finalProject_Report (BARC-Jerin)_final
Project_Report (BARC-Jerin)_finalJerin John
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008Luis Enrique
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3Mahmoud Ouf
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Tomas Petricek
 
Advanced full text searching techniques using Lucene
Advanced full text searching techniques using LuceneAdvanced full text searching techniques using Lucene
Advanced full text searching techniques using LuceneAsad Abbas
 

Semelhante a Linq (20)

Linq
LinqLinq
Linq
 
Link quries
Link quriesLink quries
Link quries
 
B_110500002
B_110500002B_110500002
B_110500002
 
C# advanced topics and future - C#5
C# advanced topics and future - C#5C# advanced topics and future - C#5
C# advanced topics and future - C#5
 
Linq in C#
Linq in C#Linq in C#
Linq in C#
 
Linq
LinqLinq
Linq
 
Linq
LinqLinq
Linq
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
 
Project_Report (BARC-Jerin)_final
Project_Report (BARC-Jerin)_finalProject_Report (BARC-Jerin)_final
Project_Report (BARC-Jerin)_final
 
Intake 37 linq2
Intake 37 linq2Intake 37 linq2
Intake 37 linq2
 
ORM - Ivan Marković
ORM - Ivan MarkovićORM - Ivan Marković
ORM - Ivan Marković
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
 
#CNX14 - Intro to Force
#CNX14 - Intro to Force#CNX14 - Intro to Force
#CNX14 - Intro to Force
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
 
Greg Demo Slides
Greg Demo SlidesGreg Demo Slides
Greg Demo Slides
 
Advanced full text searching techniques using Lucene
Advanced full text searching techniques using LuceneAdvanced full text searching techniques using Lucene
Advanced full text searching techniques using Lucene
 
Beginning linq
Beginning linqBeginning linq
Beginning linq
 

Último

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Último (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Linq

  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 9.
  • 10. Language Features That Support LINQ Query Expressions Query expressions in Visual Basic 2008 can be expressed in a declarative syntax similar to that of SQL or XQuery. At compile time, query syntax is converted into method calls to a LINQ provider's implementation of the standard query operator extension methods. Applications control which standard query operators are in scope by specifying the appropriate namespace with an Imports statement. Syntax for a Visual Basic query expression looks like this: Dim londonCusts = From cust In customers _ Where cust.City = &quot;London&quot; _ Order By cust.Name Ascending _ Select cust.Name, cust.Phone
  • 11. LINQ Query Syntax Shaping the output select <expression> Projection Aggregate the source items count([<expression>]), sum(<expression>), min(<expression>), max (<expression>), avg(<expression>) Aggregate Control the ordering of the results order by <expression>, <expression> [Ascending | Descending] Order Expression specifying the selection Criteria where <expression>, distinct Filter Information source providing a set of item (s) from <item> in <data source> Source Using type inference to assign the resulting value(s) var <variable> = Destination
  • 12. Language Features That Support LINQ Implicitly Typed Variables Instead of explicitly specifying a type when you declare and initialize a variable, you can now enable the compiler to infer and assign the type, as shown in the following example. This is referred to as local type inference. ' The variable number will be typed as an integer. Dim aNumber = 5 ' The variable name will be typed as a String . Dim aName = &quot;Virginia&quot;
  • 13. Language Features That Support LINQ Object Initializers Object initializers are used in query expressions when you have to create an anonymous type to hold the results of a query. They also can be used to initialize objects of named types outside of queries. By using an object initializer, you can initialize an object in a single line without explicitly calling a constructor. Assuming that you have a class named Customer that has public Name and Phone properties, along with other properties, an object initializer can be used in this manner: Dim aCust As Customer = New Customer With {.Name = &quot;Mike&quot;, _ .Phone = &quot;555-0212&quot;}
  • 14. Language Features That Support LINQ Anonymous Types Anonymous types provide a convenient way to temporarily group a set of properties into an element that you want to include in a query result. This enables you to choose any combination of available fields in the query, in any order, without defining a named data type for the element. An anonymous type is constructed dynamically by the compiler. The name of the type is assigned by the compiler, and it might change with each new compilation. Therefore, the name cannot be used directly. Anonymous types are initialized in the following way: ' Outside a query. Dim product = New With {.Name = &quot;paperclips&quot;, .Price = 1.29} ' Inside a query. ' You can use the existing member names of the selected fields, as was ' shown previously in the Query Expressions section of this topic. Dim londonCusts1 = From cust In customers_ Where cust.City = &quot;London“ _ Select cust.Name, cust.Phone ' Or you can specify new names for the selected fields. Dim londonCusts2 = From cust In customers _ Where cust.City = &quot;London&quot; _ Select CustomerName = cust.Name, _ CustomerPhone = cust.Phone
  • 15. Language Features That Support LINQ Extension Methods Extension methods enable you to add methods to a data type or interface from outside the definition. This feature enables you to, in effect, add new methods to an existing type without actually modifying the type. The standard query operators are themselves a set of extension methods that provide LINQ query functionality for any type that implements IEnumerable(Of T) . Other extensions to IEnumerable(Of T) include  Count , Union , and Intersect . ' Import System.Runtime.CompilerServices to use the Extension attribute. <Extension()> _ Public Sub Print(ByVal str As String) Console.WriteLine(str) End Sub Dim greeting As String = &quot;Hello&quot; greeting.Print() The following extension method adds a print method to the String class. The method is called like an ordinary instance method of String :
  • 16. Language Features That Support LINQ Lambda Expressions A lambda expression is a function without a name that calculates and returns a single value. Unlike named functions, a lambda expression can be defined and executed at the same time. The following example displays 4. Console.WriteLine((Function(num As Integer) num + 1)(3)) You can assign the lambda expression definition to a variable name and then use the name to call the function. The following example also displays 4. Dim add1 = Function(num As Integer) num + 1 Console.WriteLine(add1(3)) In LINQ, lambda expressions underlie many of the standard query operators. The compiler creates lambda expressions to capture the calculations that are defined in fundamental query methods such as Where, Select, Order By, Take While, and others. For example, the following code defines a query that returns all senior students from a list of students. Dim seniorsQuery = From stdnt In students Where stdnt.Year = &quot;Senior&quot; Select stdnt The query definition is compiled into code that is similar to the following example, which uses two lambda expressions to specify the arguments for Where and Select. Dim seniorsQuery2 = students Where(Function(st) st.Year = &quot;Senior&quot;) Select(Function(s) s)
  • 17. More On Queries Like normal SQL queries we can do the following operations by using LINQ expressions Describes the Skip clause, which bypasses a specified number of elements in a collection and then returns the remaining elements. Skip Clause Describes the Select clause, which declares a set of range variables for a query Select Clause Describes the Order By clause, which specifies the sort order for columns in a query. Order By Clause Describes the Let clause, which computes a value and assigns it to a new variable in the query. Let Clause Describes the Join clause, which combines two collections into a single collection. Join Clause Describes the Group Join clause, which combines two collections into a single hierarchical collection. Group Join Clause Describes the Group By clause, which groups the elements of a query result and can be used to apply aggregate functions to each group. Group By Clause Describes the From clause, which specifies a collection and a range variable for a query. From Clause Describes the Distinct clause, which restricts the values of the current range variable to eliminate duplicate values in query results. Distinct Clause Describes the Aggregate clause, which applies one or more aggregate functions to a collection Aggregate Clause Descriptions Clause Name
  • 18. More On Queries Like normal SQL queries we can do the following operations by using LINQ expressions Describes the Skip While clause, which bypasses elements in a collection as long as a specified condition is true and then returns the remaining elements. Skip While Clause Describes the Where clause, which specifies a filtering condition for a query. Where Clause Describes the Take While clause, which includes elements in a collection as long as a specified condition is true and bypasses the remaining elements. Take While Describes the Take clause, which returns a specified number of contiguous elements from the start of a Collection Take Descriptions Clause Name
  • 19. Queries – Order By Clause Specifies the sort order for a query result. Syntax: Order By orderExp1 [ Ascending | Descending ] [, orderExp2 [...] ] Example The following query expression uses a From clause to declare a range variable book for the books collection. The Order By clause sorts the query result by price in ascending order (the default). Books with the same price are sorted by title in ascending order. The Select clause selects only the Title property as the value returned by the query. Dim titlesAscendingPrice = From book In books Order By book.Price, book.Title Select book.Title, book.Price The following query expression uses the Order By clause to sort the query result by price in descending order. Books with the same price are sorted by title in ascending order. Dim titlesDescendingPrice = From book In books Order By book.Price Descending, book.Title _ Select book.Title, book.Price Dim bookOrders = From book In books Select book.Title, book.Price, book.PublishDate, book.Author _ Order By Author, Title, Price
  • 20. Queries – Distinct By Clause Restricts the values of the current range variable to eliminate duplicate values in subsequent query clauses. You can use the Distinct clause to return a list of unique items. The Distinct clause causes the query to ignore duplicate query results. The Distinct clause applies to duplicate values for all return fields specified by the Select clause. If no Select clause is specified, the Distinct clause is applied to the range variable for the query identified in the From clause. If the range variable is not an immutable type, the query will only ignore a query result if all members of the type match an existing query result. Example The following query expression joins a list of customers and a list of customer orders. The Distinct clause is included to return a list of unique customer names and order dates. Dim customerOrders = From cust In customers, ord In orders _ Where cust.CustomerID = ord.CustomerID _ Select cust.CompanyName, ord.OrderDate Distinct
  • 21. Queries – From Clause Specifies one or more range variables and a collection to query. Syntax: From element [ As type ] In collection [ _ ] [, element2 [ As type2 ] In collection2 [, ... ] ] Example: Dim customersForRegion = From cust In customers You can specify multiple From clauses in a query to identify multiple collections to be joined. When multiple collections are specified, they are iterated over independently, or you can join them if they are related. You can join collections implicitly by using the Select clause, or explicitly by using the Join or Group Join clauses. As an alternative, you can specify multiple range variables and collections in a single From clause, with each related range variable and collection separated from the others by a comma. The following code example shows both syntax options for the From clause.
  • 22. Queries – From Clause Continue … ' Multiple From clauses in a query. Dim result = From var1 In collection1, var2 In collection2 ' Equivalent syntax with a single From clause. Dim result2 = From var1 In collection1 _ From var2 In collection2 The From clause defines the scope of a query, which is similar to the scope of a For loop. Therefore, each element range variable in the scope of a query must have a unique name. Because you can specify multiple From clauses for a query, subsequent From clauses can refer to range variables in the From clause, or they can refer to range variables in a previous From clause. For example, the following example shows a nested From clause where the collection in the second clause is based on a property of the range variable in the first clause. Dim allOrders = From cust In GetCustomerList() _ From ord In cust.Orders _ Select ord Dim customersForRegion = From cust In customers _ Where cust.Region = region
  • 25.
  • 26. Queering Dataset Single Table Queries The following example gets all the online orders from the SalesOrderHeader table and outputs the order ID, order date, and order number to the console. ' Fill the DataSet. Dim ds As New DataSet() ds.Locale = CultureInfo.InvariantCulture ' See the FillDataSet method in the Loading Data Into a DataSet topic. FillDataSet(ds) Dim orders As DataTable = ds.Tables(&quot;SalesOrderHeader&quot;) Dim query = From order In orders.AsEnumerable() _ Where order.Field(Of Boolean)(&quot;OnlineOrderFlag&quot;) = True _ Select New With { _ .SalesOrderID = order.Field(Of Integer)(&quot;SalesOrderID&quot;), _ .OrderDate = order.Field(Of DateTime)(&quot;OrderDate&quot;), _ .SalesOrderNumber = order.Field(Of String)(&quot;SalesOrderNumber&quot;) _ } For Each onlineOrder In query Console.Write(&quot;Order ID: &quot; & onlineOrder.SalesOrderID) Console.Write(&quot; Order date: &quot; & onlineOrder.OrderDate) Console.WriteLine(&quot; Order number: &quot; & onlineOrder.SalesOrderNumber) Next
  • 27. Queering Dataset Accessing Values without using Field method Dim products As DataTable = ds.Tables(&quot;Product&quot;) Dim query = _ From product In products.AsEnumerable() _ Where product!Color IsNot DBNull.Value AndAlso product!Color = &quot;Red&quot; _ Select New With _ { _ .Name = product!Name, _ .ProductNumber = product!ProductNumber, _ .ListPrice = product!ListPrice _ } For Each product In query Console.WriteLine(&quot;Name: &quot; & product.Name) Console.WriteLine(&quot;Product number: &quot; & product.ProductNumber) Console.WriteLine(&quot;List price: $&quot; & product.ListPrice & vbNewLine) Next
  • 28. Queering Dataset Accessing Values using Field method Dim products As DataTable = ds.Tables(&quot;Product&quot;) Dim query = _ From product In products.AsEnumerable() _ Where product.Field(Of String)(&quot;Color&quot;) = &quot;Red&quot; _ Select New With _ { _ .Name = product.Field(Of String)(&quot;Name&quot;), _ .ProductNumber = product.Field(Of String)(&quot;ProductNumber&quot;), _ .ListPrice = product.Field(Of Decimal)(&quot;ListPrice&quot;) _ } For Each product In query Console.WriteLine(&quot;Name: &quot; & product.Name) Console.WriteLine(&quot;Product number: &quot; & product.ProductNumber) Console.WriteLine(&quot;List price: $ &quot; & product.ListPrice & vbNewLine) Next
  • 29. Queering Dataset Advantage of using Field method and SetField method The Field method provides access to the column values of a DataRow and the SetField sets column values in a DataRow . Both the Field method and SetField method handle nullable types, so you do not have to explicitly check for null values as in the previous example. Both methods are generic methods, also, so you do not have to cast the return type.
  • 30. Queering Dataset Cross-Table Queries The Language-Integrated Query (LINQ) framework provides two join operators,  Join  and GroupJoin . These operators perform equi-joins: that is, joins that match two data sources only when their keys are equal. (By contrast, Transact-SQL supports join operators other than equals, such as the less than operator.)  In relational database terms, Join implements an inner join. An inner join is a type of join in which only those objects that have a match in the opposite data set are returned. The GroupJoin operators have no direct equivalent in relational database terms; they implement a superset of inner joins and left outer joins. A left outer join is a join that returns each element of the first (left) collection, even if it has no correlated elements in the second collection.
  • 31. Queering Dataset Cross-Table Queries Dim orders As DataTable = ds.Tables(&quot;SalesOrderHeader&quot;) Dim details As DataTable = ds.Tables(&quot;SalesOrderDetail&quot;) Dim query = _ From order In orders.AsEnumerable() _ Join detail In details.AsEnumerable() _ On order.Field(Of Integer)(&quot;SalesOrderID&quot;) Equals _ detail.Field(Of Integer)(&quot;SalesOrderID&quot;) _ Where order.Field(Of Boolean)(&quot;OnlineOrderFlag&quot;) = True And _ order.Field(Of DateTime)(&quot;OrderDate&quot;).Month = 8 _ Select New With _ { _ .SalesOrderID = order.Field(Of Integer)(&quot;SalesOrderID&quot;), _ .SalesOrderDetailID = detail.Field(Of Integer)(&quot;SalesOrderDetailID&quot;), _ .OrderDate = order.Field(Of DateTime)(&quot;OrderDate&quot;), _ .ProductID = detail.Field(Of Integer)(&quot;ProductID&quot;) _ } For Each order In query Console.WriteLine(order.SalesOrderID & vbTab & _ order.SalesOrderDetailID & vbTab & _ order.OrderDate & vbTab & _ order.ProductID) Next
  • 32. Queering Dataset Querying Typed DataSets A typed DataSet is a class that derives from a DataSet. As such, it inherits all the methods, events, and properties of a DataSet. Additionally, a typed DataSet provides strongly typed methods, events, and properties. This means you can access tables and columns by name, instead of using collection-based methods. Aside from the improved readability of the code, a typed DataSet also allows the Visual Studio .NET code editor to automatically complete lines as you type. Additionally, the strongly typed DataSet provides access to values as the correct type at compile time. With a strongly typed DataSet, type mismatch errors are caught when the code is compiled rather than at run time. Typed DataSets LINQ to DataSet also supports querying over a typed DataSet . With a typed DataSet , you do not have to use the generic Field method or SetField method to access column data.  Property names are available at compile time because the type information is included in the DataSet . LINQ to DataSet provides access to column values as the correct type, so that type mismatch errors are caught when the code is compiled instead of at run time.
  • 33. Queering Dataset Querying Typed DataSets Dim orders = ds.Tables(&quot;SalesOrderHeader&quot;) Dim query = _ From o In orders _ Where o.OnlineOrderFlag = True _ Select New {SalesOrderID := o.SalesOrderID, _ OrderDate := o.OrderDate, _ SalesOrderNumber := o.SalesOrderNumber} For Each Dim onlineOrder In query Console.WriteLine(&quot;{0}{1:d}{2}&quot;, _ onlineOrder.SalesOrderID, _ onlineOrder.OrderDate, _ onlineOrder.SalesOrderNumber) Next