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

LINQ Inside

  • 1.
    LINQ Inside 赵劼 http://jeffreyzhao.cnblogs.com jeffz@live.com
  • 2.
    About Me • ShanghaiBaisheng 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 isfor 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 • Isit just a db access technology? • Is it just a piece of “syntactic sugar”?
  • 6.
  • 7.
    “I’ll never useC# 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 • LanguageIntegrated 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 LambdaExpression Anonymous Class … THINGS RELATED TO LINQ
  • 14.
    Extension Method • “syntacticsugar” – 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 • Inlinedelegates 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 • Functionalprogramming 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 areall 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 cando 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 Expressionfor Anonymous method DEMO 1
  • 20.
    Expression Tree • AGREAT 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 • Seewhat 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 ConstructExpression 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 forExpression Tree Construct an Expression Tree Programically DEMO 2
  • 27.
    Question • What’s thedifference 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 lambdaexpression in the first code snippet represents an Anonymous Method • The lambda expression in the second code snippet constructs an Expression Tree
  • 29.
    Now we knowabout Extension Method and Lambda Expression, but… Where’s LINQ?
  • 30.
    Please wait forthe second part of the session… 
  • 31.
    Next, We’ll FocusMore 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