C# 3.0 and 3.5 for experienced developers.

Python developers are probably already familiar with List Comprehensions, and lambda expressions. The interesting twist with LINQ is these expressions are translated into SQL and executed on the RDBMS instead of being done on the client side. There was a pretty clever Python project that achieved this in Python through dissassembly of python bytecodes, but I can’t recall it’s name [Update 23 Apr 2008: see http://svn.aminus.net/dejavu/branches/ldap/logic.py ] . There are some interesting ideas raised in LINQ that even Python developers ought to explore and consider adopting in a future Python. [Edit: 23 Apr 2008: Meaning I'd prefer to see this in Python core through AST transformation rather than bytecode hacks, C# has just got macros.]

  1. Setting up a Linq DataContext

    MyDatabaseContext db = new MyDatabaseContext(MyConnectionString); // or MyDatabaseContext db = new MyDatabaseContext();
     
  2. Basic LINQ Expression

    var AnIQueryable = from Customer in db.Customers
    where Customer.FirstName.StartsWith("m")
    select Customer; 
  3. Logging the generated queries

    db.Log = Console.out

    The previous example translates into a LIKE operator:

    SELECT [t0].[CustomerID], [t0].[FirstName] AS [FirstName]
    FROM [dbo].[Customer] AS [t0]
    WHERE [t0].[FirstName] LIKE @p0

  4. LINQ with Aggregates

    var AverageRuns =(from Master in this.db.Masters select Master.Runs).Average()
    

    The SQL generated isn’t too shabby either:

    SELECT AVG([t0].[Runs]) AS [value]
    FROM [dbo].[Master] AS [t0]
  5. LINQ grouped aggregates

    
       var categories =
          from p in products
          group p by p.Category into g
          select new
                  {Category = g.Key,
                   AveragePrice = g.Group.Average(p => p.UnitPrice)
                   };
    
  6. Lambda Expressions

    • Map

      db.Customers.Select(customer => master.Customer.LastName.length)
    • Filter

      db.Customers.Where(customer => customer.LastName.StartsWith("M")
    • Reduce / Fold


      double[] doubles = { 1.7, 2.4, 3.5, 8.9 };
      double result = doubles.Aggregate(0.0, (d1, d2) => d1+d2);

      Note: You can’t use Aggregate directly on IQueryable from database contexts. Instead,

      var arr_masters = this.db.Masters.ToArray();
      var totalRuns = arr_masters.Aggregate
      (0, // seed
      (int accum, MyDB.Master master) => accum + master.Runs
      );

  7. Updating Database

    
    this.Validate();
    this.masterBindingSource.EndEdit();
    db.SubmitChanges();
    
  8. How to cheat

    Use Microsoft’s 101 LINQ samples

 

Leave a Reply