SlideShare a Scribd company logo
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 (20)

PDF
Functional Reactive Programming in Clojurescript
Leonardo Borges
 
PDF
Introduction to Asynchronous scala
Stratio
 
PDF
Gatling - Paris Perf User Group
slandelle
 
PPTX
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
PDF
Swift and Kotlin Presentation
Andrzej Sitek
 
PDF
Swift for-rubyists
Michael Yagudaev
 
PDF
What To Expect From PHP7
Codemotion
 
PPTX
Modern JS with ES6
Kevin Langley Jr.
 
PPTX
Why TypeScript?
FITC
 
PDF
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
PDF
The algebra of library design
Leonardo Borges
 
PPTX
Code generation with javac plugin
Oleksandr Radchykov
 
PDF
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
PDF
Node Boot Camp
Troy Miles
 
PDF
JavaScript Execution Context
Juan Medina
 
PDF
scala-gopher: async implementation of CSP for scala
Ruslan Shevchenko
 
PPTX
Understanding Javascript Engines
Parashuram N
 
PDF
How much performance can you get out of Javascript? - Massimiliano Mantione -...
Codemotion
 
PPTX
History of asynchronous in .NET
Marcin Tyborowski
 
Functional Reactive Programming in Clojurescript
Leonardo Borges
 
Introduction to Asynchronous scala
Stratio
 
Gatling - Paris Perf User Group
slandelle
 
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
Swift and Kotlin Presentation
Andrzej Sitek
 
Swift for-rubyists
Michael Yagudaev
 
What To Expect From PHP7
Codemotion
 
Modern JS with ES6
Kevin Langley Jr.
 
Why TypeScript?
FITC
 
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
TypeScript Introduction
Dmitry Sheiko
 
The algebra of library design
Leonardo Borges
 
Code generation with javac plugin
Oleksandr Radchykov
 
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
Node Boot Camp
Troy Miles
 
JavaScript Execution Context
Juan Medina
 
scala-gopher: async implementation of CSP for scala
Ruslan Shevchenko
 
Understanding Javascript Engines
Parashuram N
 
How much performance can you get out of Javascript? - Massimiliano Mantione -...
Codemotion
 
History of asynchronous in .NET
Marcin Tyborowski
 

Viewers also liked (20)

PDF
企业开发领域的语言特性
jeffz
 
PDF
The Evolution of Async Programming (GZ TechParty C#)
jeffz
 
PDF
分布式版本管理
jeffz
 
PDF
Jscex:案例、阻碍、体会、展望
jeffz
 
PDF
JavaScript现代化排错实践
jeffz
 
PDF
Web开发中的缓存
jeffz
 
PDF
大话程序员可用的算法
jeffz
 
PPT
Ruby Past, Present, Future
adamfine
 
PDF
Rabbit mq簡介(上)
共和 薛
 
PPTX
QML 與 C++ 的美麗邂逅
Jack Yang
 
PDF
Storm特性
zyh
 
PDF
鐵道女孩向前衝-RubyKaigi心得分享
Yu-Chen Chen
 
PDF
LWC15 典藏數位化-張其昀先生相關資料數位化之應用 報告人:中國文化大學圖書館 吳瑞秀館長
International Federation for information integration
 
PDF
臺北智慧城市專案辦公室公共住宅智慧社區服務說明書工作會議--智慧圖書館
Taipei Smart City PMO
 
PDF
我編譯故我在:誰說 Node.js 程式不能編成 binary
Fred Chien
 
PPTX
LWC14夢醒時分:圖書館建築構想書的實踐成果 以國立臺東大學圖書館為例。報告人:國立臺東大學圖書館 吳錦範組長
International Federation for information integration
 
PDF
Brig:Node.js + QML 華麗大冒險
Fred Chien
 
PDF
計概:Programming Paradigm
Rex Yuan
 
PPTX
新時代圖書館大未來
Ted Lin (林泰宏)
 
PDF
超酷炫科幻 UI:QML 入門
Fred Chien
 
企业开发领域的语言特性
jeffz
 
The Evolution of Async Programming (GZ TechParty C#)
jeffz
 
分布式版本管理
jeffz
 
Jscex:案例、阻碍、体会、展望
jeffz
 
JavaScript现代化排错实践
jeffz
 
Web开发中的缓存
jeffz
 
大话程序员可用的算法
jeffz
 
Ruby Past, Present, Future
adamfine
 
Rabbit mq簡介(上)
共和 薛
 
QML 與 C++ 的美麗邂逅
Jack Yang
 
Storm特性
zyh
 
鐵道女孩向前衝-RubyKaigi心得分享
Yu-Chen Chen
 
LWC15 典藏數位化-張其昀先生相關資料數位化之應用 報告人:中國文化大學圖書館 吳瑞秀館長
International Federation for information integration
 
臺北智慧城市專案辦公室公共住宅智慧社區服務說明書工作會議--智慧圖書館
Taipei Smart City PMO
 
我編譯故我在:誰說 Node.js 程式不能編成 binary
Fred Chien
 
LWC14夢醒時分:圖書館建築構想書的實踐成果 以國立臺東大學圖書館為例。報告人:國立臺東大學圖書館 吳錦範組長
International Federation for information integration
 
Brig:Node.js + QML 華麗大冒險
Fred Chien
 
計概:Programming Paradigm
Rex Yuan
 
新時代圖書館大未來
Ted Lin (林泰宏)
 
超酷炫科幻 UI:QML 入門
Fred Chien
 
Ad

Similar to LINQ Inside (20)

PPT
C#3.0 & Vb 9.0 New Features
techfreak
 
PPT
Understanding linq
Anand Kumar Rajana
 
PPT
LINQ.ppt
Ponnieaswari M.S
 
PPTX
Linq and lambda
John Walsh
 
ODP
New c sharp3_features_(linq)_part_iv
Nico Ludwig
 
PDF
C# 3.0 and 4.0
Buu Nguyen
 
PDF
linq with Exampls
Jitendra Gangwar
 
PPT
C# 3.0 and LINQ Tech Talk
Michael Heydt
 
PDF
Module 3: Introduction to LINQ (Material)
Mohamed Saleh
 
PPT
Of Lambdas and LINQ
BlackRabbitCoder
 
PDF
Beginning linq
Shikha Gupta
 
PPTX
Linq (from the inside)
Mike Clement
 
PPTX
Think in linq
Sudipta Mukherjee
 
PDF
New c sharp3_features_(linq)_part_ii
Nico Ludwig
 
PDF
New c sharp3_features_(linq)_part_iv
Nico Ludwig
 
PPTX
LINQ.pptx
IrfanPinjari2
 
PPTX
C# advanced topics and future - C#5
Peter Gfader
 
PPTX
Linq Introduction
Neeraj Kaushik
 
KEY
Linq Refresher
buildmaster
 
C#3.0 & Vb 9.0 New Features
techfreak
 
Understanding linq
Anand Kumar Rajana
 
Linq and lambda
John Walsh
 
New c sharp3_features_(linq)_part_iv
Nico Ludwig
 
C# 3.0 and 4.0
Buu Nguyen
 
linq with Exampls
Jitendra Gangwar
 
C# 3.0 and LINQ Tech Talk
Michael Heydt
 
Module 3: Introduction to LINQ (Material)
Mohamed Saleh
 
Of Lambdas and LINQ
BlackRabbitCoder
 
Beginning linq
Shikha Gupta
 
Linq (from the inside)
Mike Clement
 
Think in linq
Sudipta Mukherjee
 
New c sharp3_features_(linq)_part_ii
Nico Ludwig
 
New c sharp3_features_(linq)_part_iv
Nico Ludwig
 
LINQ.pptx
IrfanPinjari2
 
C# advanced topics and future - C#5
Peter Gfader
 
Linq Introduction
Neeraj Kaushik
 
Linq Refresher
buildmaster
 
Ad

More from jeffz (20)

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

Recently uploaded (20)

PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PDF
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PPTX
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
PPTX
Machine Learning Benefits Across Industries
SynapseIndia
 
PPTX
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
introduction to computer hardware and sofeware
chauhanshraddha2007
 
PDF
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
PDF
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
The Future of Artificial Intelligence (AI)
Mukul
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
Machine Learning Benefits Across Industries
SynapseIndia
 
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
introduction to computer hardware and sofeware
chauhanshraddha2007
 
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 

LINQ Inside

  • 1. LINQ Inside 赵劼 http://jeffreyzhao.cnblogs.com [email protected]
  • 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