Thursday, April 7, 2011

c# Linq Compound Froms

I’m a bit embarrassed to admit this, but even after using linq in it’s various form for a couple of years now, I hadn’t really ever noticed compound from expressions e.g.

   1:  public void Linq16()
   2:  {
   3:      List<Customer> customers = GetCustomerList();
   5:      var orders =
   6:          from c in customers
   7:          from o in c.Orders
   8:          where o.OrderDate >= new DateTime(1998, 1, 1)
   9:          select new { c.CustomerID, o.OrderID, o.OrderDate };
  11:      ObjectDumper.Write(orders);
  12:  }

(from 101 LINQ samples)

Very handy for flattening an object hierarchy, etc. In the end though it’s just syntactic sugar over SelectMany (like a good deal of many LINQ functions). Anyway, another tool in the belt.

1 comment:

  1. "from/SelectMany" in linq is just the monadic bind operator. In typical linq, you're just using the List monad. But you can also create your own SelectMany and thereby create your own monadic syntax as well. It's pretty cool -- google around for how to make the Maybe monad in LINQ. Probably 20-30 lines of code and you can avoid null reference errors from cropping up in the middle of things like "x = object.SubObject.SubSubObject.SoOn" by writing:

    var x = from obj in object
    from so in obj.SubObject
    from sso in so.SubSubObject
    from soOn in sso.SoOn
    select soOn;

    x will equal soOn if that whole chain exists, or it will equal null if any of those subobjects is null. Very handy.