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();
   4:   
   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 };
  10:   
  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.

0 comments:

Post a Comment