SlideShare a Scribd company logo
1 of 32
Download to read offline
LINQ Inside

              赵劼
http://jeffreyzhao.cnblogs.com
         jeffz@live.com
About Me
• Shanghai Baisheng Technology Co., Ltd.
• Architect? Programmer!
  – Be a happy programmer
• 日写代码三百行,不辞长作程序员
• Have fun with the technology
• Good at losing weight.
  – Lost 40kg in 10 months
The session is for you if…
• You know nothing about LINQ.
• You don’t like LINQ.
• You want to learn how LINQ works in real
  world.
• You’re not using LINQ for any reasons
Agenda
•   LINQ and the related things
•   LINQ inside.
•   Performance tips
•   Advanced usages
•   Others
What’s LINQ
• Is it just a db access technology?
• Is it just a piece of “syntactic sugar”?
NO!
“I’ll never use C# without LINQ”
                                    - Dflying Chen
                                                   CTO
                        Shanghai Baisheng Tech Co., Ltd.
var odd =
  from i in new int[] { 1, 2, 3, 4, 5 }
  where i % 2 != 0
  select i;

WHAT’S LINQ
About LINQ
• Language Integrated Query
• Since .NET Framework 3.5 with C# 3.0/VB 9.0
• The technology combined serveral others
  – Extension Method
  – Lambda Expression
  – Anonymous Method
  – Anonymous Class
  – etc.
LINQ to…
• LINQ != LINQ to SQL
  – A new way to access and manipulate data
  – Not only the data in SQL Server
• What can we “LINQ to”?
  – LINQ to SQL
  – LINQ to XML
  – LINQ to Object
  – LINQ to Entity (from MS ADO.NET Entity Fx)
• And we can also…
LINQ to… (Cont.)
•   LINQ to Google
•   LINQ to System Search
•   LINQ to NHibernate
•   LINQ to Active Directory
•   LINQ to Lucene
•   LINQ to Flickr
•   LINQ to Excel
•   and more and more and more…
Some Concerpts
• LINQ
• LINQ to SQL
• LINQ Provider

• http://jeffreyzhao.cnblogs.com/archive/2008/
  06/04/ajax-linq-lambda-expression.html
Extension Method
Anonymous Method
Lambda Expression
Anonymous Class
…

THINGS RELATED TO LINQ
Extension Method
• “syntactic sugar” – I agree with that.
• More elegant programming style
                                       public static class StringExtensions{
                                           public static string HtmlEncode(this s){
                                               return HttpUtility.HtmlEncode(s);
                                           }
<%=                                    }
      HttpUtility.HtmlEncode(
          "<script>…</script>")   =>
%>

                                       <%=
                                             "<script>…</script>".HtmlEnocde();
                                       %>
Anonymous Method
• Inline delegates without method declaration
• Can easily access the local variables
  – Magic of compiler

          void SomeMethod {
              int intVar;
              Action action = delegate() { intVar = 10; };
              action();
          }
Lambda Expression
• Functional programming style
• “=>” operator
• A lambda expression can represent:
  – An anonymous method
  – An expression tree
  – http://jeffreyzhao.cnblogs.com/archive/2008/06/
    04/ajax-linq-lambda-expression.html
Things below are all equivalent

Func<int, int, bool> predicate = delegate(int x, int y) { return x > y; };


Func<int, int, bool> predicate = (x, y) => { return x > y; };


Func<int, int, bool> predicate = (x, y) => x > y;
And we can do more like…

 Func<int, int, bool> predicate = (x, y) => {
     var dayService = new DayService();
     if (dayService.IsApirlFools(DateTime.Today)){
         return x < y;
     } else {
         return x > y;
     }
 };
Extension Method
Lambda Expression for Anonymous method

DEMO 1
Expression Tree
• A GREAT way to represent in lots of scenarios
• Can be constructed by lambda expression in
  compile time
• Can also be constructed programically
  – Lambda expression would be convert to this by
    compiler
         System.Linq.Expressions.Expression<TDelegate>
Expression Tree Samples
Expression<Func<int>> constantExpr = () => 5;

Expression<Func<int, int, int>> simpleExpr = (x, y) => x + y;

Expression<Func<int, int, bool>> complexExpr =
    (x, y) => new Random(DateTime.Now.Millisecond).Next(x) > y;
Programmically Construction
• See what complier do for us…
   Expression<Func<int, int>> negateExpr = x => -x;




   ParameterExpression param = Expression.Parameter(typeof(int), "x");
   Expression<Func<int, int>> negateExpr =
       Expression.Lambda<Func<int, int>>(
           Expression.Negate(param),
           new ParameterExpression[] { param });
Expression Hierarchy
System.Linq.Expressions.Expression
  BinaryExpression
  ConditionalExpression
  ConstantExpression
  InvocationExpression
  LambdaExpression
  MemberExpression
  MethodCallExpression
  NewExpression
  NewArrayExpression
  MemberInitExpression
  ListInitExpression
  ParameterExpression
  TypeBinaryExpression
  UnaryExpression
The Factory Methods
• There’re factory methods in Expression class for
  us to build an Expression Tree.
• Examples
  – New: Creates a NewExpression.
  – Negate: Creates a UnaryExpression that represents an
    arithmetic negation operation
  – And: Creates a BinaryExpression that represents a
    bitwise AND operation.
  – ArrayIndex: Creates an Expression that represents
    applying an array index operator.
Tips of Construct Expression Trees
• Process
  – Preparing parameter expressions at first.
  – Construct the body of expression tree with the
    factory methods.
  – Wrap the whole expression body with
    LambdaExpression at the end.
• Tools can help us
  – Expression Tree Visualizer
  – .NET Reflector (a must-have for .NET programmer)
Lambda Expression for Expression Tree
Construct an Expression Tree Programically

DEMO 2
Question
• What’s the difference between these two?
  var intList = new List<int>() { 1, 2, 3, 4, 5 };
  foreach (int i in intList.Where(i => i % 2 == 1))
  {
      Console.WriteLine(i);
  }



  var intList = new List<int>() { 1, 2, 3, 4, 5 }.AsQueryable();
  foreach (int i in intList.Where(i => i % 2 == 1))
  {
      Console.WriteLine(i);
  }
Answer:
• The lambda expression in the first code
  snippet represents an Anonymous Method
• The lambda expression in the second code
  snippet constructs an Expression Tree
Now we know about Extension Method and
        Lambda Expression, but…

            Where’s LINQ?
Please wait for the
second part of the session…
            
Next, We’ll Focus More on…
• LINQ
  – Usage
  – Pros & Cons
• Performance
  – Benchmark
  – Improvements
• Advanced topics
  – Use Expression Tree in different scenarios.
  – LINQ Provider
• Others
References
•   http://msdn.microsoft.com
•   http://en.wikipedia.org/wiki/Linq
•   http://rednaxelafx.javaeye.com/blog/237822
•   http://code.msdn.microsoft.com/csharpsampl
    es

More Related Content

What's hot

Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
Stratio
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
Andrzej Sitek
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 

What's hot (20)

Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in Clojurescript
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
 
Gatling - Paris Perf User Group
Gatling - Paris Perf User GroupGatling - Paris Perf User Group
Gatling - Paris Perf User Group
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Swift for-rubyists
Swift for-rubyistsSwift for-rubyists
Swift for-rubyists
 
What To Expect From PHP7
What To Expect From PHP7What To Expect From PHP7
What To Expect From PHP7
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library design
 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac plugin
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
 
scala-gopher: async implementation of CSP for scala
scala-gopher:  async implementation of CSP  for  scalascala-gopher:  async implementation of CSP  for  scala
scala-gopher: async implementation of CSP for scala
 
Understanding Javascript Engines
Understanding Javascript Engines Understanding Javascript Engines
Understanding Javascript Engines
 
How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 

Viewers also liked

企业开发领域的语言特性
企业开发领域的语言特性企业开发领域的语言特性
企业开发领域的语言特性
jeffz
 
The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)
jeffz
 
分布式版本管理
分布式版本管理分布式版本管理
分布式版本管理
jeffz
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践
jeffz
 
大话程序员可用的算法
大话程序员可用的算法大话程序员可用的算法
大话程序员可用的算法
jeffz
 
我編譯故我在:誰說 Node.js 程式不能編成 binary
我編譯故我在:誰說 Node.js 程式不能編成 binary我編譯故我在:誰說 Node.js 程式不能編成 binary
我編譯故我在:誰說 Node.js 程式不能編成 binary
Fred Chien
 
基于原型的JavaScript面向对象编程
基于原型的JavaScript面向对象编程基于原型的JavaScript面向对象编程
基于原型的JavaScript面向对象编程
zhangdaiping
 

Viewers also liked (20)

企业开发领域的语言特性
企业开发领域的语言特性企业开发领域的语言特性
企业开发领域的语言特性
 
The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)
 
分布式版本管理
分布式版本管理分布式版本管理
分布式版本管理
 
Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践
 
Web开发中的缓存
Web开发中的缓存Web开发中的缓存
Web开发中的缓存
 
大话程序员可用的算法
大话程序员可用的算法大话程序员可用的算法
大话程序员可用的算法
 
Ruby Past, Present, Future
Ruby   Past, Present, FutureRuby   Past, Present, Future
Ruby Past, Present, Future
 
Rabbit mq簡介(上)
Rabbit mq簡介(上)Rabbit mq簡介(上)
Rabbit mq簡介(上)
 
QML 與 C++ 的美麗邂逅
QML 與 C++ 的美麗邂逅QML 與 C++ 的美麗邂逅
QML 與 C++ 的美麗邂逅
 
Storm特性
Storm特性Storm特性
Storm特性
 
鐵道女孩向前衝-RubyKaigi心得分享
鐵道女孩向前衝-RubyKaigi心得分享鐵道女孩向前衝-RubyKaigi心得分享
鐵道女孩向前衝-RubyKaigi心得分享
 
LWC15 典藏數位化-張其昀先生相關資料數位化之應用 報告人:中國文化大學圖書館 吳瑞秀館長
LWC15 典藏數位化-張其昀先生相關資料數位化之應用 報告人:中國文化大學圖書館 吳瑞秀館長LWC15 典藏數位化-張其昀先生相關資料數位化之應用 報告人:中國文化大學圖書館 吳瑞秀館長
LWC15 典藏數位化-張其昀先生相關資料數位化之應用 報告人:中國文化大學圖書館 吳瑞秀館長
 
臺北智慧城市專案辦公室公共住宅智慧社區服務說明書工作會議--智慧圖書館
臺北智慧城市專案辦公室公共住宅智慧社區服務說明書工作會議--智慧圖書館臺北智慧城市專案辦公室公共住宅智慧社區服務說明書工作會議--智慧圖書館
臺北智慧城市專案辦公室公共住宅智慧社區服務說明書工作會議--智慧圖書館
 
我編譯故我在:誰說 Node.js 程式不能編成 binary
我編譯故我在:誰說 Node.js 程式不能編成 binary我編譯故我在:誰說 Node.js 程式不能編成 binary
我編譯故我在:誰說 Node.js 程式不能編成 binary
 
LWC14夢醒時分:圖書館建築構想書的實踐成果 以國立臺東大學圖書館為例。報告人:國立臺東大學圖書館 吳錦範組長
LWC14夢醒時分:圖書館建築構想書的實踐成果 以國立臺東大學圖書館為例。報告人:國立臺東大學圖書館 吳錦範組長LWC14夢醒時分:圖書館建築構想書的實踐成果 以國立臺東大學圖書館為例。報告人:國立臺東大學圖書館 吳錦範組長
LWC14夢醒時分:圖書館建築構想書的實踐成果 以國立臺東大學圖書館為例。報告人:國立臺東大學圖書館 吳錦範組長
 
Brig:Node.js + QML 華麗大冒險
Brig:Node.js + QML 華麗大冒險Brig:Node.js + QML 華麗大冒險
Brig:Node.js + QML 華麗大冒險
 
基于原型的JavaScript面向对象编程
基于原型的JavaScript面向对象编程基于原型的JavaScript面向对象编程
基于原型的JavaScript面向对象编程
 
計概:Programming Paradigm
計概:Programming Paradigm計概:Programming Paradigm
計概:Programming Paradigm
 
新時代圖書館大未來
新時代圖書館大未來新時代圖書館大未來
新時代圖書館大未來
 

Similar to LINQ Inside

Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
Nayden Gochev
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
Intro to javascript (6:19)
Intro to javascript (6:19)Intro to javascript (6:19)
Intro to javascript (6:19)
Thinkful
 

Similar to LINQ Inside (20)

Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
Java 8
Java 8Java 8
Java 8
 
What’s expected in Spring 5
What’s expected in Spring 5What’s expected in Spring 5
What’s expected in Spring 5
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
MWLUG 2015 - AD114 Take Your XPages Development to the Next Level
MWLUG 2015 - AD114 Take Your XPages Development to the Next LevelMWLUG 2015 - AD114 Take Your XPages Development to the Next Level
MWLUG 2015 - AD114 Take Your XPages Development to the Next Level
 
SQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET FundamentalsSQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET Fundamentals
 
The joy of functional programming
The joy of functional programmingThe joy of functional programming
The joy of functional programming
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Intro to javascript (6:19)
Intro to javascript (6:19)Intro to javascript (6:19)
Intro to javascript (6:19)
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
ELAG Workshop version 1
ELAG Workshop version 1ELAG Workshop version 1
ELAG Workshop version 1
 
L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
 
Write tests, please
Write tests, pleaseWrite tests, please
Write tests, please
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Microservices Chaos Testing at Jet
Microservices Chaos Testing at JetMicroservices Chaos Testing at Jet
Microservices Chaos Testing at Jet
 

More from jeffz

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错
jeffz
 
Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望
jeffz
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
jeffz
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developers
jeffz
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
jeffz
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
jeffz
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
jeffz
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现
jeffz
 
Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程
jeffz
 
Windows Phone应用开发心得
Windows Phone应用开发心得Windows Phone应用开发心得
Windows Phone应用开发心得
jeffz
 
针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构
jeffz
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
jeffz
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
面向对象与生活
面向对象与生活面向对象与生活
面向对象与生活
jeffz
 
Windows内核技术介绍
Windows内核技术介绍Windows内核技术介绍
Windows内核技术介绍
jeffz
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
jeffz
 
如何成为一名优秀的博主
如何成为一名优秀的博主如何成为一名优秀的博主
如何成为一名优秀的博主
jeffz
 

More from jeffz (20)

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错
 
Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developers
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现
 
Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程
 
Windows Phone应用开发心得
Windows Phone应用开发心得Windows Phone应用开发心得
Windows Phone应用开发心得
 
针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
面向对象与生活
面向对象与生活面向对象与生活
面向对象与生活
 
Windows内核技术介绍
Windows内核技术介绍Windows内核技术介绍
Windows内核技术介绍
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
大众点评网的技术变迁之路
大众点评网的技术变迁之路大众点评网的技术变迁之路
大众点评网的技术变迁之路
 
Better Framework Better Life
Better Framework Better LifeBetter Framework Better Life
Better Framework Better Life
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
如何成为一名优秀的博主
如何成为一名优秀的博主如何成为一名优秀的博主
如何成为一名优秀的博主
 

Recently uploaded

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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
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
 
"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 ...
 
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
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

LINQ Inside

  • 1. LINQ Inside 赵劼 http://jeffreyzhao.cnblogs.com jeffz@live.com
  • 2. About Me • Shanghai Baisheng Technology Co., Ltd. • Architect? Programmer! – Be a happy programmer • 日写代码三百行,不辞长作程序员 • Have fun with the technology • Good at losing weight. – Lost 40kg in 10 months
  • 3. The session is for you if… • You know nothing about LINQ. • You don’t like LINQ. • You want to learn how LINQ works in real world. • You’re not using LINQ for any reasons
  • 4. Agenda • LINQ and the related things • LINQ inside. • Performance tips • Advanced usages • Others
  • 5. What’s LINQ • Is it just a db access technology? • Is it just a piece of “syntactic sugar”?
  • 6. NO!
  • 7. “I’ll never use C# without LINQ” - Dflying Chen CTO Shanghai Baisheng Tech Co., Ltd.
  • 8. var odd = from i in new int[] { 1, 2, 3, 4, 5 } where i % 2 != 0 select i; WHAT’S LINQ
  • 9. About LINQ • Language Integrated Query • Since .NET Framework 3.5 with C# 3.0/VB 9.0 • The technology combined serveral others – Extension Method – Lambda Expression – Anonymous Method – Anonymous Class – etc.
  • 10. LINQ to… • LINQ != LINQ to SQL – A new way to access and manipulate data – Not only the data in SQL Server • What can we “LINQ to”? – LINQ to SQL – LINQ to XML – LINQ to Object – LINQ to Entity (from MS ADO.NET Entity Fx) • And we can also…
  • 11. LINQ to… (Cont.) • LINQ to Google • LINQ to System Search • LINQ to NHibernate • LINQ to Active Directory • LINQ to Lucene • LINQ to Flickr • LINQ to Excel • and more and more and more…
  • 12. Some Concerpts • LINQ • LINQ to SQL • LINQ Provider • http://jeffreyzhao.cnblogs.com/archive/2008/ 06/04/ajax-linq-lambda-expression.html
  • 13. Extension Method Anonymous Method Lambda Expression Anonymous Class … THINGS RELATED TO LINQ
  • 14. Extension Method • “syntactic sugar” – I agree with that. • More elegant programming style public static class StringExtensions{ public static string HtmlEncode(this s){ return HttpUtility.HtmlEncode(s); } <%= } HttpUtility.HtmlEncode( "<script>…</script>") => %> <%= "<script>…</script>".HtmlEnocde(); %>
  • 15. Anonymous Method • Inline delegates without method declaration • Can easily access the local variables – Magic of compiler void SomeMethod { int intVar; Action action = delegate() { intVar = 10; }; action(); }
  • 16. Lambda Expression • Functional programming style • “=>” operator • A lambda expression can represent: – An anonymous method – An expression tree – http://jeffreyzhao.cnblogs.com/archive/2008/06/ 04/ajax-linq-lambda-expression.html
  • 17. Things below are all equivalent Func<int, int, bool> predicate = delegate(int x, int y) { return x > y; }; Func<int, int, bool> predicate = (x, y) => { return x > y; }; Func<int, int, bool> predicate = (x, y) => x > y;
  • 18. And we can do more like… Func<int, int, bool> predicate = (x, y) => { var dayService = new DayService(); if (dayService.IsApirlFools(DateTime.Today)){ return x < y; } else { return x > y; } };
  • 19. Extension Method Lambda Expression for Anonymous method DEMO 1
  • 20. Expression Tree • A GREAT way to represent in lots of scenarios • Can be constructed by lambda expression in compile time • Can also be constructed programically – Lambda expression would be convert to this by compiler System.Linq.Expressions.Expression<TDelegate>
  • 21. Expression Tree Samples Expression<Func<int>> constantExpr = () => 5; Expression<Func<int, int, int>> simpleExpr = (x, y) => x + y; Expression<Func<int, int, bool>> complexExpr = (x, y) => new Random(DateTime.Now.Millisecond).Next(x) > y;
  • 22. Programmically Construction • See what complier do for us… Expression<Func<int, int>> negateExpr = x => -x; ParameterExpression param = Expression.Parameter(typeof(int), "x"); Expression<Func<int, int>> negateExpr = Expression.Lambda<Func<int, int>>( Expression.Negate(param), new ParameterExpression[] { param });
  • 23. Expression Hierarchy System.Linq.Expressions.Expression BinaryExpression ConditionalExpression ConstantExpression InvocationExpression LambdaExpression MemberExpression MethodCallExpression NewExpression NewArrayExpression MemberInitExpression ListInitExpression ParameterExpression TypeBinaryExpression UnaryExpression
  • 24. The Factory Methods • There’re factory methods in Expression class for us to build an Expression Tree. • Examples – New: Creates a NewExpression. – Negate: Creates a UnaryExpression that represents an arithmetic negation operation – And: Creates a BinaryExpression that represents a bitwise AND operation. – ArrayIndex: Creates an Expression that represents applying an array index operator.
  • 25. Tips of Construct Expression Trees • Process – Preparing parameter expressions at first. – Construct the body of expression tree with the factory methods. – Wrap the whole expression body with LambdaExpression at the end. • Tools can help us – Expression Tree Visualizer – .NET Reflector (a must-have for .NET programmer)
  • 26. Lambda Expression for Expression Tree Construct an Expression Tree Programically DEMO 2
  • 27. Question • What’s the difference between these two? var intList = new List<int>() { 1, 2, 3, 4, 5 }; foreach (int i in intList.Where(i => i % 2 == 1)) { Console.WriteLine(i); } var intList = new List<int>() { 1, 2, 3, 4, 5 }.AsQueryable(); foreach (int i in intList.Where(i => i % 2 == 1)) { Console.WriteLine(i); }
  • 28. Answer: • The lambda expression in the first code snippet represents an Anonymous Method • The lambda expression in the second code snippet constructs an Expression Tree
  • 29. Now we know about Extension Method and Lambda Expression, but… Where’s LINQ?
  • 30. Please wait for the second part of the session… 
  • 31. Next, We’ll Focus More on… • LINQ – Usage – Pros & Cons • Performance – Benchmark – Improvements • Advanced topics – Use Expression Tree in different scenarios. – LINQ Provider • Others
  • 32. References • http://msdn.microsoft.com • http://en.wikipedia.org/wiki/Linq • http://rednaxelafx.javaeye.com/blog/237822 • http://code.msdn.microsoft.com/csharpsampl es