Road to Dynamic LINQ Part 1

Download Road to Dynamic LINQ Part 1

Post on 15-Apr-2017




0 download


Axilis template

Road to Dynamic LINQVedran Mari AKA FosnaWarning: Expression Trees Ahead

About me Vedran Mari AKA Fosnadev at

organizing programming workshops for kidsLogo, Scratch, HTML, CSS, JavaScript, Python, C++

Well coverPart 1What is expression tree in C#How is it different from similar looking lambda delegatesHow to build expression treesHow to parse expression treesWhere are you already using them

Part 2Check out few expression tree exploitsPoint to brilliant, not easy to understand, ideas or projects from some cool developer maniacs

We wont coverImplementing LINQ providersImplementing deep copyImplementing faster static dictionaryImplementing IoC container

Introduction to Expression Trees

Expression Tree NodesPlain old C#c = a + b

Lambda expression (a, b) => a + b

Gists: AddStatement.linqSimpleBinaryExpression.linq

Definitionrepresent code in a tree-like data structurenot in MSIL (Microsoft Intermediate Language)each node is an expressionhas compiler smell all over itcan compile to get functions!get some good ol MSILMSIL ex:

IL_0007: ldloc.0 // a IL_0008: ldloc.1 // b IL_0009: add IL_000A: stloc.2 // c

HistoryCame with .NET 3.5Built some muscle in .NET 4.0nuff said

Expression Tree Dissection

x => x < 5Gist: SimpleLogicalExpression.linq

Why Expression Tree?

analyze expression treediscover what you want donedecide how to do it

Expression Trees Vs Lambda DelegatesOne lambda expression

(a, b) => a + b

Expression Trees Vs Lambda DelegatesOne lambda expression

(a, b) => a + b

Two type signatures

Expression Trees Vs Lambda Delegates


Gist: TreeVsDelegate.linq

Applied Expression Trees Vs Lambda DelegatesWhich technology exploits expression trees and which one doesnt?LINQ to ObjectsLINQ to Entities (EF)LINQ to XMLParallel LINQ

How to Create an Expression Tree?From lambda expression at compile timeMethod invocation flavor

Query syntaxUsing Expression API at run timeWhy would anyone do that?

Gist: BuildExp.linq

Famous Extension Methods...attached to Clever Interfaces

Lazy: AsEnumerable()

If code can be executed in process then the job can be done with the simple type called IEnumerableremember yield return

Lazy: AsQueryable()

If you need to translate a query expression into a string that will be passed to another process, then use IQueryable and expression trees.

Eager Extension MethodsToList()ToArray()ToDictionary()ToLookup()


Applied Expression TreesNext time...

Thanks. Bye!No questions, right?

ResourcesStart with Tree Basics, Charlie Calvert 31 Jan 2008 3:49 AM by Olexander Ivanitskyi on Tuesday, June 11, 2013 LINQ: Func vs. Expression Apr 27 '09 at 13:50, Richard NagleWhy would you use Expression rather than Func?

ResourcesC# 6.0 Features Functions .NET Programmers Playground - LinqPad