SlideShare une entreprise Scribd logo
1  sur  45
Chuck Durfee, 3 October 2012
BIG
DATA
Enumerable.Select(
Enumerable.OrderBy(
Enumerable.Where(names, s => s.Length == 5),
s => s
),
s => s.ToUpper()
);
versus
names.Where(s => s.Length == 5)
.OrderBy(s => s)
.Select(s => s.ToUpper())
, my dear Watson
1.0
delegate bool FilterMethod(string s);
private bool IsFiveLetterName(string s) {
return s.Length == 5;
}
public DotNet10Land()
{
FilterMethod filter = IsFiveLetterName;
}
delegate bool FilterMethod(string s);
public DotNet20Land()
{
FilterMethod filter =
delegate(string s) {
return s.Length == 5;
};
}
2.0
C# 3 = .NET 3.5
delegate bool FilterMethod(string s);
public DotNet35Land()
{
string chuck = "chuck";
FilterMethod filter =
delegate(string s) {
return s != chuck && s.Length == 5;
};
}
Func
// delegate bool FilterMethod(string s);
public DotNet35Land()
{
Func<string, bool> filter =
delegate(string s) {
return s.Length == 5;
};
}
Func<string, bool>
Func<string, int, DateTime>
Func<List<string>, int, bool>
but not
Func<string, System.Void>
// delegate void ActionMethod(string s);
public DotNet35Land()
{
Action<string> action = delegate(string s) {
if (s.Length != 5)
throw new ArgumentException("Length != 5");
};
}
and… Action
LAMBDA EXPRESSIONS
Func<string, bool> filter =
delegate(string s) {return s.Length == 5;};
var filter = (string s) => {return s.Length == 5;};
var filter = (string s) => s.Length == 5;
var filter = (s) => s.Length == 5;
var filter = s => s.Length == 5;
by Alonzo Church, 1930’s
string[] names = { "Tom", "Dick",
"Harry" };
names.Select((s, i) =>
(i + 1) + "=" + s);
1=Tom
2=Dick
3=Harry
int[] numbers = { 3, 5, 7 };
string[] words = { "three", "five",
"seven", "ignored" };
IEnumerable<string> zip =
numbers.Zip(words,
(n, w) => n + "=" + w);
3=three
5=five
7=seven
IEnumerable<Order> spanishOrders =
customers
.Where(c => c.Country == "Spain")
.SelectMany(c => c.Orders);
var slowQuery =
from c in customers
from p in purchases where c.ID == p.CustomerID
select c.Name + " bought a " + p.Description;
var fastQuery =
from c in customers
join p in purchases on c.ID equals p.CustomerID
select c.Name + " bought a " + p.Description;
var easyToRead =
from c in customers
join p in purchases on c.ID equals p.CustomerID
select c.Name + " bought a " + p.Description;
var harderToRead = customers.Join (
purchases,
c => (int?)(c.ID),
p => p.CustomerID,
(c, p) => ((c.Name + " bought a ") +
p.Description)
);
public static class EnumerableExtensions
{
public static string ToCsv<T>(
this IEnumerable<T> sequence)
{
const string delimiter = ", ";
return sequence.Aggregate(
new StringBuilder(),
(sb, s) => sb.Append(s + delimiter),
sb => sb.ToString()
.TrimEnd(delimiter.ToArray()));
}
}
new[] { 1, 2, 3, 5, 8, 13, 20 } => 1, 2, 3, 5, 8, 13, 20
LINQ
LINQ

Contenu connexe

Tendances

Python data structures
Python data structuresPython data structures
Python data structures
Harry Potter
 
The MongoDB Driver for F#
The MongoDB Driver for F#The MongoDB Driver for F#
The MongoDB Driver for F#
MongoDB
 

Tendances (15)

PDBC
PDBCPDBC
PDBC
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Card pack
Card packCard pack
Card pack
 
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
 
Card pack
Card packCard pack
Card pack
 
ETL for Pros: Getting Data Into MongoDB
ETL for Pros: Getting Data Into MongoDBETL for Pros: Getting Data Into MongoDB
ETL for Pros: Getting Data Into MongoDB
 
Ass2 1 (2)
Ass2 1 (2)Ass2 1 (2)
Ass2 1 (2)
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Intro
IntroIntro
Intro
 
Vcs16
Vcs16Vcs16
Vcs16
 
Multiplicacion de polinomios 1ro
Multiplicacion de polinomios   1roMultiplicacion de polinomios   1ro
Multiplicacion de polinomios 1ro
 
밑바닥부터 시작하는 의료 AI
밑바닥부터 시작하는 의료 AI밑바닥부터 시작하는 의료 AI
밑바닥부터 시작하는 의료 AI
 
The MongoDB Driver for F#
The MongoDB Driver for F#The MongoDB Driver for F#
The MongoDB Driver for F#
 
The Ring programming language version 1.5.3 book - Part 20 of 184
The Ring programming language version 1.5.3 book - Part 20 of 184The Ring programming language version 1.5.3 book - Part 20 of 184
The Ring programming language version 1.5.3 book - Part 20 of 184
 

Similaire à LINQ

c++ program for Railway reservation
c++ program for Railway reservationc++ program for Railway reservation
c++ program for Railway reservation
Swarup Kumar Boro
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
aleks-f
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
HIMANSUKUMAR12
 
Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01
google
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 

Similaire à LINQ (20)

Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
c++ program for Railway reservation
c++ program for Railway reservationc++ program for Railway reservation
c++ program for Railway reservation
 
Railway reservation
Railway reservationRailway reservation
Railway reservation
 
Артём Акуляков - F# for Data Analysis
Артём Акуляков - F# for Data AnalysisАртём Акуляков - F# for Data Analysis
Артём Акуляков - F# for Data Analysis
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 
C++ Programming - 1st Study
C++ Programming - 1st StudyC++ Programming - 1st Study
C++ Programming - 1st Study
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
 
Automatically Spotting Cross-language Relations
Automatically Spotting Cross-language RelationsAutomatically Spotting Cross-language Relations
Automatically Spotting Cross-language Relations
 
Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01
 
The Ring programming language version 1.7 book - Part 28 of 196
The Ring programming language version 1.7 book - Part 28 of 196The Ring programming language version 1.7 book - Part 28 of 196
The Ring programming language version 1.7 book - Part 28 of 196
 
Keygenning using the Z3 SMT Solver
Keygenning using the Z3 SMT SolverKeygenning using the Z3 SMT Solver
Keygenning using the Z3 SMT Solver
 
Generics and Lambdas cocktail explained - Montreal JUG
Generics and Lambdas cocktail explained  - Montreal JUGGenerics and Lambdas cocktail explained  - Montreal JUG
Generics and Lambdas cocktail explained - Montreal JUG
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
C arrays
C arraysC arrays
C arrays
 
The Ring programming language version 1.10 book - Part 33 of 212
The Ring programming language version 1.10 book - Part 33 of 212The Ring programming language version 1.10 book - Part 33 of 212
The Ring programming language version 1.10 book - Part 33 of 212
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210
 
Grails - The search is over
Grails - The search is overGrails - The search is over
Grails - The search is over
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 

Dernier

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 

LINQ

  • 1. Chuck Durfee, 3 October 2012
  • 2.
  • 3.
  • 5.
  • 6.
  • 7.
  • 8. Enumerable.Select( Enumerable.OrderBy( Enumerable.Where(names, s => s.Length == 5), s => s ), s => s.ToUpper() ); versus names.Where(s => s.Length == 5) .OrderBy(s => s) .Select(s => s.ToUpper())
  • 9.
  • 10. , my dear Watson
  • 11.
  • 12. 1.0 delegate bool FilterMethod(string s); private bool IsFiveLetterName(string s) { return s.Length == 5; } public DotNet10Land() { FilterMethod filter = IsFiveLetterName; }
  • 13. delegate bool FilterMethod(string s); public DotNet20Land() { FilterMethod filter = delegate(string s) { return s.Length == 5; }; } 2.0
  • 14. C# 3 = .NET 3.5 delegate bool FilterMethod(string s); public DotNet35Land() { string chuck = "chuck"; FilterMethod filter = delegate(string s) { return s != chuck && s.Length == 5; }; }
  • 15.
  • 16. Func // delegate bool FilterMethod(string s); public DotNet35Land() { Func<string, bool> filter = delegate(string s) { return s.Length == 5; }; }
  • 17. Func<string, bool> Func<string, int, DateTime> Func<List<string>, int, bool> but not Func<string, System.Void>
  • 18. // delegate void ActionMethod(string s); public DotNet35Land() { Action<string> action = delegate(string s) { if (s.Length != 5) throw new ArgumentException("Length != 5"); }; } and… Action
  • 19. LAMBDA EXPRESSIONS Func<string, bool> filter = delegate(string s) {return s.Length == 5;}; var filter = (string s) => {return s.Length == 5;}; var filter = (string s) => s.Length == 5; var filter = (s) => s.Length == 5; var filter = s => s.Length == 5;
  • 20. by Alonzo Church, 1930’s
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32. string[] names = { "Tom", "Dick", "Harry" }; names.Select((s, i) => (i + 1) + "=" + s); 1=Tom 2=Dick 3=Harry
  • 33.
  • 34. int[] numbers = { 3, 5, 7 }; string[] words = { "three", "five", "seven", "ignored" }; IEnumerable<string> zip = numbers.Zip(words, (n, w) => n + "=" + w); 3=three 5=five 7=seven
  • 35.
  • 36. IEnumerable<Order> spanishOrders = customers .Where(c => c.Country == "Spain") .SelectMany(c => c.Orders);
  • 37.
  • 38. var slowQuery = from c in customers from p in purchases where c.ID == p.CustomerID select c.Name + " bought a " + p.Description; var fastQuery = from c in customers join p in purchases on c.ID equals p.CustomerID select c.Name + " bought a " + p.Description;
  • 39.
  • 40. var easyToRead = from c in customers join p in purchases on c.ID equals p.CustomerID select c.Name + " bought a " + p.Description; var harderToRead = customers.Join ( purchases, c => (int?)(c.ID), p => p.CustomerID, (c, p) => ((c.Name + " bought a ") + p.Description) );
  • 41.
  • 42.
  • 43. public static class EnumerableExtensions { public static string ToCsv<T>( this IEnumerable<T> sequence) { const string delimiter = ", "; return sequence.Aggregate( new StringBuilder(), (sb, s) => sb.Append(s + delimiter), sb => sb.ToString() .TrimEnd(delimiter.ToArray())); } } new[] { 1, 2, 3, 5, 8, 13, 20 } => 1, 2, 3, 5, 8, 13, 20

Notes de l'éditeur

  1. Let’s talk about the history of LINQ
  2. C# 2 introduced generics, at that point, C# is feature complete from an OO perspective
  3. Next challenge to tackle after OO features is Big Data, how to reduce complexity of integrating information
  4. Have to juggle translation between database constructs and objects
  5. Easy way to query data source Extension methods, query comprehension syntax Way to return arbitrary results Anonymous types, var keyword Way to pass input data Closures, collection and object initializers
  6. May be too complicated to know at design time, but known at compile time. For more flexibility, you need dynamics and the DLR in .NET 4.
  7. For the last piece of the puzzle, let’s talk about variable binding
  8. http://www.paintingsoncanvas.net/print-111552-4043120/stone-age-man-making-weapon-giclee-print/
  9. http://www.travelwalls.net/wallpapers/2012/08/Walt-Disney-Concert-Hall-Modern-City-Los-Angeles-California-United-States-300x420.jpg
  10. Don’t need to declare a delegate…
  11. System.Void isn’t a true Type Image: http://www.efunda.com/math/bessel/images/BesselJPlot.gif
  12. Need a separate generic delegate for void return methods Image: http://portcityfilmfestival.com/clap-board.jpg
  13. Distill down to simpler forms, all equivalent Image: http://watermarked.cutcaster.com/cutcaster-photo-100783484-Lambda-symbol-in-glass-3d.jpg
  14. The term lambdas comes from lambda calculus. Instead of set-based theories like Venn diagrams, Church wanted to look at it from a functional design perspective.
  15. Take the number 5
  16. I could express that as a function that always returns 5
  17. This is more like Church’s notation
  18. In an operation like adding, I can substitute the functions for the numbers
  19. If I can do that, adding itself can be defined as a function. Adding has no side effects. 5 is still 5 after I use it while adding.
  20. If you take this to its logical conclusion, any group of operations can be expressed as a hierarchy of functions – which C# calls Expression Trees.
  21. But if that’s true, it makes sense that I can write some function-by-function transformations that turn a C# function into a SQL function…
  22. With a provider of transformations, I can take queries in C# and turn them into queries against a bunch of different data sources. .NET ships with a few, but you can write others.
  23. Now to the practical side of things….
  24. Here, I use LINQPad (http://linqpad.com) to demonstrate Where and the like.
  25. Map or Project is a functional-language based description of the operation. We call it Select because of most C# programmers’ “SQL heritage”.
  26. Select can take a position argument. Many LINQ operators have overloads, check them out.
  27. Zip can replace simple Join statements.
  28. Like fibers in a thread, binding with SelectMany takes many sets and combines them into one.
  29. With Select, this would look like { {Andy’s orders}, {Beth’s orders}, {Charlie’s orders}…} With SelectMany, this would look like { Andy1, Andy2, Beth1, Charlie1, Charlie2…}
  30. SelectMany is like doing a cross join in SQL, whereas Join is an inner join
  31. Easy to Read is query comprehension syntax. It came from the Entity Framework folks that were also working on this data query problem. Hard to Read is extension methods.
  32. Skip and Take allow you to “page” through your data. There’s also SkipWhile and TakeWhile.
  33. Examples include Count(), Sum()…
  34. Here, I show the Aggregate command.
  35. Included in .NET 4.5 or can be downloaded as an external library in .NET 4 Use ToParallel() to invoke PLINQ
  36. Image: http://cdn.abovethelaw.com/uploads/2012/02/thank-you.jpg