SlideShare a Scribd company logo
1 of 51
LINQ:
Language-Integrated Queries
(To be included in C# 3.0)
2
LINQ
• A C# language extension:
– Use SQL-like syntax in C#.
• Outline:
– Examples
– Understanding the witchcraft
• Delegate functions
• Lambda expressions
• Type inference
• Anonymous types
• Extension methods
• Expression trees
3
Searching in Collections
• Begin with a simple array of, say,
Customers.
Customer[] customers = new Customer[30];
customers[0] = new Customer(…);
…
customers[29] = new Customer(…);
4
Searching in Collections:
The Old Way
• Find the names of all London customers:
List<string> londoners = new List<string>();
foreach (Customer c in customers) {
if (c.City == “London”) {
londoners.add(c.Name);
}
}
5
Searching in Collections:
The LINQ Way
string[] londoners =
from c in customers
where c.City == “London”
select c.Name;
Declarative!
SQL-like!
No loops!
Returns a simple array!
6
LINQ: How Does It Work?
• LINQ syntax = shorthand for method
invocation.
• “Translation maps”
7
Syntax Translation Example
string[] londoners =
from c in customers
where c.City == “London”
select c.Name;
string[] londoners =
customers.
Where(expression).
Select(expression);
8
Translating Expressions
• Problem: Translating
“c.City == “London””
to an expression e, such that Where(e) is
valid?
9
Expressions == Methods?
• Where() wants a Boolean method.
• The method acts as a filter.
• Likewise for Select(): a translation
method.
10
C# Delegates
• C# delegates: method pointers.
class Demo {
delegate void Foo();
void Bar() { … do something … };
void Test() {
Foo myDelegate = new Foo(Bar);
// “pointer” to Bar()
myDelegate(); // invoke
}
}
11
Delegates as Arguments
• Delegates can be passed as arguments.
– Event handlers, jobs for threads, etc.
class Demo {
void Job() { … the job to carry out … };
void Test() {
Thread worker = new Thread(
new ThreadStart(Job));
worker.start();
}
}
12
Anonymous Methods
• Nameless methods = on-the-fly delegates:
class Demo {
delegate void Foo();
void Test() {
Foo myDelegate = delegate() {
… do something …
};
myDelegate(); // invoke
}
}
13
Syntax Translation Example
string[] londoners =
from c in customers
where c.City == “London”
select c.Name;
string[] londoners =
customers.
Where(delegate(Customer c) {
return c.City == “London”; }).
Select(delegate(Customer c) {
return c.Name });
14
Well, Not Really.
•Where(), etc. accept delegate
methods.
• But LINQ creates lambda
expressions.
• Seamless conversion.
15
Syntax Translation Example
string[] londoners =
from c in customers
where c.City == “London”
select c.Name;
string[] londoners =
customers.
Where(c => c.City == “London”).
Select(c => c.Name);
16
Lambda Expressions
• Lambda expression syntax:
(argumentList) => expression
oneArgument => expression
• Arguments optionally typed.
– Type inference mechanism.
– More on that later…
Shades of ML…
17
Where’s Where()?
• We invoked Where() on Customers[].
• On the resulting Customers[], we
invoked Select().
• New methods for arrays!?
18
Extension Methods
class Utils {
public static firstChar(this string s)
{
return s.charAt(0);
}
}
• So far, just a simple static method.
• Can be used like any other.
19
Extension Methods
• But now…
Using Utils;
class Demo {
void Foo() {
string s = “Hello”;
Console.WriteLine(s.firstChar());
}
}
20
Extension Methods
• Static methods that seem to extend existing
types.
• Where(), Select(), etc. extend
IEnumerable<T>.
– Defined in System.Query.
• Applicable to one-dimensional array types.
21
Query Your Own Types!
• LINQ can be applied to any type.
• Just implement Where(),
Select(), etc.
22
LINQ and Relational Data
• Let’s obtain a DB-table type, and query it.
DbCustomers c = new DbCustomers(“my.mdb”);
string[] londoners =
from c in customers
where c.City == “London”
select c.Name;
23
This Makes No Sense!
• But… Where() applies the filter to every
record.
• … on the client!
• SELECT * FROM CUSTOMERS, and
filter with a simple loop!?
24
Back To Lambda Expressions
• Lambda expressions can be converted
to anonymous methods.
• Can also be converted to expression
trees.
– A run-time representation of the syntax
tree.
25
Example…
• Our code yields:
string[] londoners = customers.
Where(c => c.City == “London”).
Select(c => c.Name);
where “customers” is of type DbCustomers.
• No
DbCustomers.Where(delegate(Customer c))
method exists.
• However:
DbCustomers.Where(
Expression<Func<Customer,bool>> xt)
26
Expression Trees
• A data type.
• Represents lambda expressions at
runtime.
• Used it to generate SQL at runtime.
– Guaranteed to be valid.
Relational Algebra:
Joins, Projections
28
Multiple Generators
(Cartesian Product / Join)
OrderData[] od = from c in customers
where c.City == “London”
from o in c.Orders
where o.OrderDate.Year == 2005
select new OrderData(c.Name, o.OrderId, o.Total);
OrderData[] od = customers.
Where(c => c.City == “London”).
SelectMany(c =>
c.Orders.
Where(o => o.OrderDate.Year == 2005).
Select(o => new OrderData(c.Name,
o.OrderId, o.Total))
);
29
Projections
• Using LINQ’s select:
from c in customers
where c.City == “London”
select
new AddressBookEntry(c.Name, c.Phone);
30
Pre-Defined Types Only?
• But…
The projection type (e.g.,
AddressBookEntry) must be pre-
defined!
31
Ad-Hoc Types
• new { [name1 =] expr1,…, [ namen =] exprn}
• Type implied by types of exprs.
• Example:
from c in customers
where c.City == “London”
select new { c.Name, c.Phone };
If name is not specified, and
expr is either property or
x.property, then property’s
name will be used.
Must not be
null-typed.
32
Ad-Hoc Types are Nameless
• How do we store the result?
??? q = from … select new {…};
• The ad-hoc type is nameless!
• Can’t use Object
– Can’t downcast to access the properties.
33
Auto-Typed Variables
• var x = 7; // x will be of type int
• var q = from … select new {…};
// q will be an array of the anonymous type
Console.WriteLine(q[0].Name);
• Local variables only.
Extra
35
Relational Data in the OO World?
• “Regular” LINQ queries yields
“rectangular” data.
• e.g.,
var od = from c in customers
where c.City == “London”
from o in c.Orders
where o.OrderDate.Year == 2005
select new { c.Name, o.OrderId, o.Total };
= multiple lines per customer.
36
Relational Data in the OO World?
100.23
122324
Joe Average
90.00
315523
Joe Average
49.95
989722
Joe Average
49.90
874366
John Smith
95.00
324777
John Smith
234.65
435882
Miss Piggy
345.21
345529
Kermit
95.95
423340
Kermit
37
OO Data in the OO World!
• Nested queries:
var od =
from c in customers
where c.City == “London”
select new {
c.Name,
Orders = from o in c.Orders
where o.OrderDate.Year == 2005
select { o.OrderId, o.Total }
};
38
OO Data in the OO World!
100.23
122324
90.00
315523
49.95
989722
Joe Average
49.90
874366
95.00
324777
John Smith
234.65
435882
Miss Piggy
345.21
345529
95.95
423340
Kermit
39
Ad-Hoc Type Equality
• Two ad-hoc type expressions that have the same
ordered set of property names and types share the
same ad-hoc type.
var p1 = new { Name = “Moo”, Age = 12 };
var p2 = new { Name = “Elk”, Age = 17 };
p1 = p2;
40
Expression Tree Generation
Expression<Func<int, bool>> exprLambda = x => (x & 1)
== 0;
ParameterExpression xParam =
Expression.Parameter(typeof(int), "x");
Expression<Func<int, bool>> exprLambda =
Expression.Lambda<Func<int, bool>>(
Expression.EQ(
Expression.BitAnd(
xParam, Expression.Constant(1)),
Expression.Constant(0)),
xParam);
41
Some LINQ Examples
from m in typeof(string).getMethods
select m.Name;
Clone
Compare
Format
CopyTo
Copy
IndexOf
IndexOf
IndexOf
Insert
Substring
Substring
…
String[]
42
Some LINQ Examples
from m in typeof(string).getMethods
where !m.IsStatic
select m.Name;
Clone
Compare
CopyTo
Copy
IndexOf
IndexOf
IndexOf
Insert
Substring
Substring
…
String[]
43
Some LINQ Examples
from m in typeof(string).getMethods
where !m.IsStatic
orderby m.name
select m.Name;
Clone
Compare
Copy
CopyTo
IndexOf
IndexOf
IndexOf
Insert
Substring
Substring
…
String[]
44
Some LINQ Examples
from m in typeof(string).getMethods
where !m.IsStatic
orderby m.name
select m.Name
groupby m.name;
Key = Clone
Key = Compare
Key = Copy
Key = CopyTo
Key = IndexOf
Key = Insert
Key = Substring
…
KeyGroupPairs[]
Group = …
Group = …
Group = …
Group = …
Group = …
Group = …
Group = …
…
45
Some LINQ Examples
from m in typeof(string).getMethods
where !m.IsStatic
orderby m.name
select m.Name
groupby m.name
into g
select new {
Method = g.Key,
Overloads = g.Group.Count
};
Name = Clone
Name = Compare
Name = Copy
Name = CopyTo
Name = IndexOf
Name = Insert
Name = Substring
…
var[]
Overloads = 1
Overloads = 2
Overloads = 1
Overloads = 1
Overloads = 5
Overloads = 3
Overloads = 6
…
46
Updates with LINQ?
• Future feature: updating capabilities.
from c in customers
where c.City == “Peking”
set c.City = “Beijing”; ??
47
DLINQ
• ADO.NET’s next-generation.
• Among other features: a database-to-
classes utility.
– Class per DB table.
– Property per DB column.
– Foreign keys, etc. reflected in the classes.
• Result: valid table/field names in the
SQL.
48
DLINQ – Roll Your Own
• You can also define your own O/R
mapping.
• By adding attributes (metadata) to
classes/fields.
• Runtime error potential.
49
Updates with DLINQ
• DLINQ-generated classes include a
change-tracking / DB updating
mechanism.
– a-la EJBs.
50
XLINQ
• Same idea, for searching in XML data.
51
Extension Methods + Boxing…
delegate void Proc();
static class TestExtensions
{
static public void Times(this Int32 n, Proc proc)
{
for (int i = 1; i <= n; i++)
proc();
}
}
Which allows you to write:
13.Times(() => Console.Write("X"));

More Related Content

Similar to LINQ.ppt

Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>corehard_by
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Anton Bikineev
 
Implementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyImplementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyMartin Odersky
 
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8Christian Nagel
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and LearnPaul Irwin
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda codePeter Lawrey
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and VariablesIntro C# Book
 
C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)Christian Nagel
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)sdrhr
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#Rohit Rao
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05CHOOSE
 

Similar to LINQ.ppt (20)

Litwin linq
Litwin linqLitwin linq
Litwin linq
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
Implementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyImplementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in Dotty
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
 
What's new in C# 8.0 (beta)
What's new in C# 8.0 (beta)What's new in C# 8.0 (beta)
What's new in C# 8.0 (beta)
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8
 
Clang tidy
Clang tidyClang tidy
Clang tidy
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and Learn
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
PostThis
PostThisPostThis
PostThis
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
 

Recently uploaded

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
#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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
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
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
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
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
#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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
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
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
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
 

LINQ.ppt

  • 2. 2 LINQ • A C# language extension: – Use SQL-like syntax in C#. • Outline: – Examples – Understanding the witchcraft • Delegate functions • Lambda expressions • Type inference • Anonymous types • Extension methods • Expression trees
  • 3. 3 Searching in Collections • Begin with a simple array of, say, Customers. Customer[] customers = new Customer[30]; customers[0] = new Customer(…); … customers[29] = new Customer(…);
  • 4. 4 Searching in Collections: The Old Way • Find the names of all London customers: List<string> londoners = new List<string>(); foreach (Customer c in customers) { if (c.City == “London”) { londoners.add(c.Name); } }
  • 5. 5 Searching in Collections: The LINQ Way string[] londoners = from c in customers where c.City == “London” select c.Name; Declarative! SQL-like! No loops! Returns a simple array!
  • 6. 6 LINQ: How Does It Work? • LINQ syntax = shorthand for method invocation. • “Translation maps”
  • 7. 7 Syntax Translation Example string[] londoners = from c in customers where c.City == “London” select c.Name; string[] londoners = customers. Where(expression). Select(expression);
  • 8. 8 Translating Expressions • Problem: Translating “c.City == “London”” to an expression e, such that Where(e) is valid?
  • 9. 9 Expressions == Methods? • Where() wants a Boolean method. • The method acts as a filter. • Likewise for Select(): a translation method.
  • 10. 10 C# Delegates • C# delegates: method pointers. class Demo { delegate void Foo(); void Bar() { … do something … }; void Test() { Foo myDelegate = new Foo(Bar); // “pointer” to Bar() myDelegate(); // invoke } }
  • 11. 11 Delegates as Arguments • Delegates can be passed as arguments. – Event handlers, jobs for threads, etc. class Demo { void Job() { … the job to carry out … }; void Test() { Thread worker = new Thread( new ThreadStart(Job)); worker.start(); } }
  • 12. 12 Anonymous Methods • Nameless methods = on-the-fly delegates: class Demo { delegate void Foo(); void Test() { Foo myDelegate = delegate() { … do something … }; myDelegate(); // invoke } }
  • 13. 13 Syntax Translation Example string[] londoners = from c in customers where c.City == “London” select c.Name; string[] londoners = customers. Where(delegate(Customer c) { return c.City == “London”; }). Select(delegate(Customer c) { return c.Name });
  • 14. 14 Well, Not Really. •Where(), etc. accept delegate methods. • But LINQ creates lambda expressions. • Seamless conversion.
  • 15. 15 Syntax Translation Example string[] londoners = from c in customers where c.City == “London” select c.Name; string[] londoners = customers. Where(c => c.City == “London”). Select(c => c.Name);
  • 16. 16 Lambda Expressions • Lambda expression syntax: (argumentList) => expression oneArgument => expression • Arguments optionally typed. – Type inference mechanism. – More on that later… Shades of ML…
  • 17. 17 Where’s Where()? • We invoked Where() on Customers[]. • On the resulting Customers[], we invoked Select(). • New methods for arrays!?
  • 18. 18 Extension Methods class Utils { public static firstChar(this string s) { return s.charAt(0); } } • So far, just a simple static method. • Can be used like any other.
  • 19. 19 Extension Methods • But now… Using Utils; class Demo { void Foo() { string s = “Hello”; Console.WriteLine(s.firstChar()); } }
  • 20. 20 Extension Methods • Static methods that seem to extend existing types. • Where(), Select(), etc. extend IEnumerable<T>. – Defined in System.Query. • Applicable to one-dimensional array types.
  • 21. 21 Query Your Own Types! • LINQ can be applied to any type. • Just implement Where(), Select(), etc.
  • 22. 22 LINQ and Relational Data • Let’s obtain a DB-table type, and query it. DbCustomers c = new DbCustomers(“my.mdb”); string[] londoners = from c in customers where c.City == “London” select c.Name;
  • 23. 23 This Makes No Sense! • But… Where() applies the filter to every record. • … on the client! • SELECT * FROM CUSTOMERS, and filter with a simple loop!?
  • 24. 24 Back To Lambda Expressions • Lambda expressions can be converted to anonymous methods. • Can also be converted to expression trees. – A run-time representation of the syntax tree.
  • 25. 25 Example… • Our code yields: string[] londoners = customers. Where(c => c.City == “London”). Select(c => c.Name); where “customers” is of type DbCustomers. • No DbCustomers.Where(delegate(Customer c)) method exists. • However: DbCustomers.Where( Expression<Func<Customer,bool>> xt)
  • 26. 26 Expression Trees • A data type. • Represents lambda expressions at runtime. • Used it to generate SQL at runtime. – Guaranteed to be valid.
  • 28. 28 Multiple Generators (Cartesian Product / Join) OrderData[] od = from c in customers where c.City == “London” from o in c.Orders where o.OrderDate.Year == 2005 select new OrderData(c.Name, o.OrderId, o.Total); OrderData[] od = customers. Where(c => c.City == “London”). SelectMany(c => c.Orders. Where(o => o.OrderDate.Year == 2005). Select(o => new OrderData(c.Name, o.OrderId, o.Total)) );
  • 29. 29 Projections • Using LINQ’s select: from c in customers where c.City == “London” select new AddressBookEntry(c.Name, c.Phone);
  • 30. 30 Pre-Defined Types Only? • But… The projection type (e.g., AddressBookEntry) must be pre- defined!
  • 31. 31 Ad-Hoc Types • new { [name1 =] expr1,…, [ namen =] exprn} • Type implied by types of exprs. • Example: from c in customers where c.City == “London” select new { c.Name, c.Phone }; If name is not specified, and expr is either property or x.property, then property’s name will be used. Must not be null-typed.
  • 32. 32 Ad-Hoc Types are Nameless • How do we store the result? ??? q = from … select new {…}; • The ad-hoc type is nameless! • Can’t use Object – Can’t downcast to access the properties.
  • 33. 33 Auto-Typed Variables • var x = 7; // x will be of type int • var q = from … select new {…}; // q will be an array of the anonymous type Console.WriteLine(q[0].Name); • Local variables only.
  • 34. Extra
  • 35. 35 Relational Data in the OO World? • “Regular” LINQ queries yields “rectangular” data. • e.g., var od = from c in customers where c.City == “London” from o in c.Orders where o.OrderDate.Year == 2005 select new { c.Name, o.OrderId, o.Total }; = multiple lines per customer.
  • 36. 36 Relational Data in the OO World? 100.23 122324 Joe Average 90.00 315523 Joe Average 49.95 989722 Joe Average 49.90 874366 John Smith 95.00 324777 John Smith 234.65 435882 Miss Piggy 345.21 345529 Kermit 95.95 423340 Kermit
  • 37. 37 OO Data in the OO World! • Nested queries: var od = from c in customers where c.City == “London” select new { c.Name, Orders = from o in c.Orders where o.OrderDate.Year == 2005 select { o.OrderId, o.Total } };
  • 38. 38 OO Data in the OO World! 100.23 122324 90.00 315523 49.95 989722 Joe Average 49.90 874366 95.00 324777 John Smith 234.65 435882 Miss Piggy 345.21 345529 95.95 423340 Kermit
  • 39. 39 Ad-Hoc Type Equality • Two ad-hoc type expressions that have the same ordered set of property names and types share the same ad-hoc type. var p1 = new { Name = “Moo”, Age = 12 }; var p2 = new { Name = “Elk”, Age = 17 }; p1 = p2;
  • 40. 40 Expression Tree Generation Expression<Func<int, bool>> exprLambda = x => (x & 1) == 0; ParameterExpression xParam = Expression.Parameter(typeof(int), "x"); Expression<Func<int, bool>> exprLambda = Expression.Lambda<Func<int, bool>>( Expression.EQ( Expression.BitAnd( xParam, Expression.Constant(1)), Expression.Constant(0)), xParam);
  • 41. 41 Some LINQ Examples from m in typeof(string).getMethods select m.Name; Clone Compare Format CopyTo Copy IndexOf IndexOf IndexOf Insert Substring Substring … String[]
  • 42. 42 Some LINQ Examples from m in typeof(string).getMethods where !m.IsStatic select m.Name; Clone Compare CopyTo Copy IndexOf IndexOf IndexOf Insert Substring Substring … String[]
  • 43. 43 Some LINQ Examples from m in typeof(string).getMethods where !m.IsStatic orderby m.name select m.Name; Clone Compare Copy CopyTo IndexOf IndexOf IndexOf Insert Substring Substring … String[]
  • 44. 44 Some LINQ Examples from m in typeof(string).getMethods where !m.IsStatic orderby m.name select m.Name groupby m.name; Key = Clone Key = Compare Key = Copy Key = CopyTo Key = IndexOf Key = Insert Key = Substring … KeyGroupPairs[] Group = … Group = … Group = … Group = … Group = … Group = … Group = … …
  • 45. 45 Some LINQ Examples from m in typeof(string).getMethods where !m.IsStatic orderby m.name select m.Name groupby m.name into g select new { Method = g.Key, Overloads = g.Group.Count }; Name = Clone Name = Compare Name = Copy Name = CopyTo Name = IndexOf Name = Insert Name = Substring … var[] Overloads = 1 Overloads = 2 Overloads = 1 Overloads = 1 Overloads = 5 Overloads = 3 Overloads = 6 …
  • 46. 46 Updates with LINQ? • Future feature: updating capabilities. from c in customers where c.City == “Peking” set c.City = “Beijing”; ??
  • 47. 47 DLINQ • ADO.NET’s next-generation. • Among other features: a database-to- classes utility. – Class per DB table. – Property per DB column. – Foreign keys, etc. reflected in the classes. • Result: valid table/field names in the SQL.
  • 48. 48 DLINQ – Roll Your Own • You can also define your own O/R mapping. • By adding attributes (metadata) to classes/fields. • Runtime error potential.
  • 49. 49 Updates with DLINQ • DLINQ-generated classes include a change-tracking / DB updating mechanism. – a-la EJBs.
  • 50. 50 XLINQ • Same idea, for searching in XML data.
  • 51. 51 Extension Methods + Boxing… delegate void Proc(); static class TestExtensions { static public void Times(this Int32 n, Proc proc) { for (int i = 1; i <= n; i++) proc(); } } Which allows you to write: 13.Times(() => Console.Write("X"));