SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
Coding with LINQ,
Patterns & Practices
 LINQ & Functional ways




                          © Tuomas Hietanen (LGPLv3)
LINQ (Monads)
• Two types of functions
  – Queries and Aggreagtes
                                                  AGGREGATE:
                                                  - returns result
   (Wrapper)           Wrapped type,
                       In this case
                       IEnumerable<T>




               QUERY:
               - returns another container of the same type
                              © Tuomas Hietanen
LINQ SELECT = LIST.MAP
                (Query)
                   MAP function:




IEnumerable<   >                            IEnumerable<   >



                        © Tuomas Hietanen
LINQ WHERE= LIST.FILTER
               (Query)
                   FILTER function:




IEnumerable<   >                             IEnumerable<   >



                         © Tuomas Hietanen
LINQ AGGREGATE= LIST.FOLD
           (Aggregate)
                   FOLD function:




IEnumerable<   >



                        © Tuomas Hietanen
Other Aggregates
             (to make things easier)

Function        Aggregate
                function
LIST.SUM        Add every
                to
LIST.COUNT      Add (+1)
                to
LIST.MAX        Select bigger of
                     or
...




                           © Tuomas Hietanen
LINQ SELECTMANY
- Not pure, has many overrides
         SELECT function:




                                   IEnumerable<   >



               © Tuomas Hietanen
LINQ SELECTMANY
- Not pure, has many overrides

    SELECT function:




                       © Tuomas Hietanen
Old Legacy Way               New C#, LINQ                     F#
var result = new List<T>(); var result = from x in xs         let result =
foreach(var x in xs){                   select …                 List.map (fun x -> ...) xs
   result.Add(...);         //same as
   ...                      var result = xs.Select(x=>...);
}
foreach(var x in xs){        var result = from x in xs        let result =
   if(x=...){...}                        where …                 List.filter(fun x -> ...) xs
}                            //same as
                             var result = xs.Where(x=>...);
var result = new T();        //many ways, based on            //many ways, based on
foreach(var x in xs){        var result = xs.Aggregate(…);    let result =
   result = ...;                                                 List.fold (fun f -> ...) xs
   ...
}                                                             //also supports unfold

foreach(var x in xs){        var result = from x in xs        //SelectMany is not pure,
  foreach(var y in ...){                  from y in …         so depends on situation.
    ....                                  select …            E.g. List.collect, or seq {...}
  }                          //same as                        let result =
}                            var result =                        List.collect (fun x -> ...) xs
                                     xs.SelectMany(...);
                                       © Tuomas Hietanen
Do use lists!
• Don’t return Null. Prefer throw
  InvalidOperationException on error and
  Enumerable.Empty<T>() on case of empty list
• Don’t modify collections, do use new ones
    list.RemoveAt(0)
    newlist = list.Where(interestingItems => ...)
• Use IEnumerable<T> not List<T> or IList<T>
  – It is the baseclass and default for LINQ
  – You can always say .toList() to evaluate the lazy
    collection.

                        © Tuomas Hietanen
Safe class design, avoid side effects
• Don’t reuse variables
     x=x+1
     y=x+1
• Avoid global and class variables. Use method
  parameters
   – Better for function composition
• Don’t overcapuslate layers or class structures
   – No coding for fun: Focus on the functionality
• Declarative programming.
   – ”yield return” is ok in some cases, but not really
     declarative.
• Also old design practices do still apply (=> FxCop).
                           © Tuomas Hietanen
F# list vs seq
• List is F# default
   – Linked list
   – Good for recursive methods
• Seq is IEnumerable<T>
   – Lazy evaluation
   – Good for .NET interop




                       © Tuomas Hietanen

Weitere ähnliche Inhalte

Was ist angesagt?

Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
Hariz Mustafa
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
Johan Tibell
 

Was ist angesagt? (20)

Understanding the components of standard template library
Understanding the components of standard template libraryUnderstanding the components of standard template library
Understanding the components of standard template library
 
Practical cats
Practical catsPractical cats
Practical cats
 
01. haskell introduction
01. haskell introduction01. haskell introduction
01. haskell introduction
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Basic Sorting algorithms csharp
Basic Sorting algorithms csharpBasic Sorting algorithms csharp
Basic Sorting algorithms csharp
 
Extensible Effects in Dotty
Extensible Effects in DottyExtensible Effects in Dotty
Extensible Effects in Dotty
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
 
Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Advance xpath
Advance xpathAdvance xpath
Advance xpath
 
Python standard data types
Python standard data typesPython standard data types
Python standard data types
 
Hackersnl
HackersnlHackersnl
Hackersnl
 

Ähnlich wie Coding with LINQ, Patterns & Practices

High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 

Ähnlich wie Coding with LINQ, Patterns & Practices (20)

03. haskell refresher quiz
03. haskell refresher quiz03. haskell refresher quiz
03. haskell refresher quiz
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
iPython
iPythoniPython
iPython
 
02. haskell motivation
02. haskell motivation02. haskell motivation
02. haskell motivation
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
On fuctional programming, high order functions, ML
On fuctional programming, high order functions, MLOn fuctional programming, high order functions, ML
On fuctional programming, high order functions, ML
 
The Ring programming language version 1.5.2 book - Part 18 of 181
The Ring programming language version 1.5.2 book - Part 18 of 181The Ring programming language version 1.5.2 book - Part 18 of 181
The Ring programming language version 1.5.2 book - Part 18 of 181
 
C# programming
C# programming C# programming
C# programming
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
 
Functional Programming and Ruby
Functional Programming and RubyFunctional Programming and Ruby
Functional Programming and Ruby
 
Fp java8
Fp java8Fp java8
Fp java8
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
The Ring programming language version 1.3 book - Part 11 of 88
The Ring programming language version 1.3 book - Part 11 of 88The Ring programming language version 1.3 book - Part 11 of 88
The Ring programming language version 1.3 book - Part 11 of 88
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Beyond xUnit example-based testing: property-based testing with ScalaCheck
Beyond xUnit example-based testing: property-based testing with ScalaCheckBeyond xUnit example-based testing: property-based testing with ScalaCheck
Beyond xUnit example-based testing: property-based testing with ScalaCheck
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
 
CppOperators.ppt
CppOperators.pptCppOperators.ppt
CppOperators.ppt
 

Mehr von Tuomas Hietanen

Mehr von Tuomas Hietanen (14)

Blockchain (using NBitcoin and FSharp)
Blockchain (using NBitcoin and FSharp)Blockchain (using NBitcoin and FSharp)
Blockchain (using NBitcoin and FSharp)
 
Machine learning (using Accord.NET and FSharp)
Machine learning (using Accord.NET and FSharp)Machine learning (using Accord.NET and FSharp)
Machine learning (using Accord.NET and FSharp)
 
Possible FSharp Refactorings could be...
Possible FSharp Refactorings could be...Possible FSharp Refactorings could be...
Possible FSharp Refactorings could be...
 
Message passing & NoSQL (in English)
Message passing & NoSQL (in English)Message passing & NoSQL (in English)
Message passing & NoSQL (in English)
 
Function therory
Function theroryFunction therory
Function therory
 
The Pain Points of C#
The Pain Points of C#The Pain Points of C#
The Pain Points of C#
 
F# references (and some misc slides)
F# references (and some misc slides)F# references (and some misc slides)
F# references (and some misc slides)
 
Linq in practice
Linq in practiceLinq in practice
Linq in practice
 
Using f# project from c#
Using f# project from c#Using f# project from c#
Using f# project from c#
 
Funktioteoriaa
FunktioteoriaaFunktioteoriaa
Funktioteoriaa
 
Pari sekalaista diaa ja F#-Referenssejä
Pari sekalaista diaa ja F#-ReferenssejäPari sekalaista diaa ja F#-Referenssejä
Pari sekalaista diaa ja F#-Referenssejä
 
F# ja C# yhteiskäyttö
F# ja C# yhteiskäyttöF# ja C# yhteiskäyttö
F# ja C# yhteiskäyttö
 
C# nykyiset kipupisteet
C# nykyiset kipupisteetC# nykyiset kipupisteet
C# nykyiset kipupisteet
 
LINQ käytännössä
LINQ käytännössäLINQ käytännössä
LINQ käytännössä
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
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
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
[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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

Coding with LINQ, Patterns & Practices

  • 1. Coding with LINQ, Patterns & Practices LINQ & Functional ways © Tuomas Hietanen (LGPLv3)
  • 2. LINQ (Monads) • Two types of functions – Queries and Aggreagtes AGGREGATE: - returns result (Wrapper) Wrapped type, In this case IEnumerable<T> QUERY: - returns another container of the same type © Tuomas Hietanen
  • 3. LINQ SELECT = LIST.MAP (Query) MAP function: IEnumerable< > IEnumerable< > © Tuomas Hietanen
  • 4. LINQ WHERE= LIST.FILTER (Query) FILTER function: IEnumerable< > IEnumerable< > © Tuomas Hietanen
  • 5. LINQ AGGREGATE= LIST.FOLD (Aggregate) FOLD function: IEnumerable< > © Tuomas Hietanen
  • 6. Other Aggregates (to make things easier) Function Aggregate function LIST.SUM Add every to LIST.COUNT Add (+1) to LIST.MAX Select bigger of or ... © Tuomas Hietanen
  • 7. LINQ SELECTMANY - Not pure, has many overrides SELECT function: IEnumerable< > © Tuomas Hietanen
  • 8. LINQ SELECTMANY - Not pure, has many overrides SELECT function: © Tuomas Hietanen
  • 9. Old Legacy Way New C#, LINQ F# var result = new List<T>(); var result = from x in xs let result = foreach(var x in xs){ select … List.map (fun x -> ...) xs result.Add(...); //same as ... var result = xs.Select(x=>...); } foreach(var x in xs){ var result = from x in xs let result = if(x=...){...} where … List.filter(fun x -> ...) xs } //same as var result = xs.Where(x=>...); var result = new T(); //many ways, based on //many ways, based on foreach(var x in xs){ var result = xs.Aggregate(…); let result = result = ...; List.fold (fun f -> ...) xs ... } //also supports unfold foreach(var x in xs){ var result = from x in xs //SelectMany is not pure, foreach(var y in ...){ from y in … so depends on situation. .... select … E.g. List.collect, or seq {...} } //same as let result = } var result = List.collect (fun x -> ...) xs xs.SelectMany(...); © Tuomas Hietanen
  • 10. Do use lists! • Don’t return Null. Prefer throw InvalidOperationException on error and Enumerable.Empty<T>() on case of empty list • Don’t modify collections, do use new ones list.RemoveAt(0) newlist = list.Where(interestingItems => ...) • Use IEnumerable<T> not List<T> or IList<T> – It is the baseclass and default for LINQ – You can always say .toList() to evaluate the lazy collection. © Tuomas Hietanen
  • 11. Safe class design, avoid side effects • Don’t reuse variables x=x+1 y=x+1 • Avoid global and class variables. Use method parameters – Better for function composition • Don’t overcapuslate layers or class structures – No coding for fun: Focus on the functionality • Declarative programming. – ”yield return” is ok in some cases, but not really declarative. • Also old design practices do still apply (=> FxCop). © Tuomas Hietanen
  • 12. F# list vs seq • List is F# default – Linked list – Good for recursive methods • Seq is IEnumerable<T> – Lazy evaluation – Good for .NET interop © Tuomas Hietanen