Expression Trees in LINQ Providers
See how providers translate expressions to queries.
Why LINQ Needs Expression Trees
LINQ has two flavors. IEnumerable<T> runs lambdas in memory. IQueryable<T> receives them as expression trees so a provider can translate them into another language, like SQL.
IEnumerable vs IQueryable
The difference is in the parameter type: IEnumerable.Where takes Func<T,bool> (compiled), while IQueryable.Where takes Expression<Func<T,bool>> (a tree).
using System;
using System.Linq;
using System.Linq.Expressions;
int[] nums = { 1, 2, 3, 4 };
// IEnumerable path: lambda is a compiled delegate
var evens = nums.Where(n => n % 2 == 0);
Console.WriteLine(string.Join(",", evens)); // 2,4All lessons in this course
- What Are Expression Trees
- Building Expressions Manually
- Compiling and Executing Expressions
- Expression Trees in LINQ Providers