LINQ with Joins

February 19, 2008 14:13 by admin

Thicktecture's Christian Nagel, has a post on LINQ with Joins.  In the post, he explains how to convert this monster:

public IEnumerable GetOrderDetails(int orderID) {
  NorthwindDataContext db = this.DataContext;
  IEnumerable orderDetails =
    from o in db.Orders
    where o.OrderID == orderID
    join s in db.Shippers on o.ShipVia equals s.ShipperID
    join od in db.OrderDetails on o.OrderID equals od.OrderID
    join p in db.Products on od.ProductID equals p.ProductID
    join supplier in db.Suppliers on p.SupplierID equals supplier.SupplierID
    let total = od.Quantity * od.UnitPrice
    select new OrderDescription
    {
      Product = p.ProductName,
      Quantity = od.Quantity,
      ShipperName = s.CompanyName,
      Total = total,
      UnitPrice = od.UnitPrice,
      SupplierName = supplier.CompanyName
    };
  return orderDetails;
}

Into the slightly more managable:

public IEnumerable GetOrderDetails(int orderID)
{
  NorthwindDataContext db = this.DataContext;
  IEnumerable orderDetails =
    from o in db.Orders
    where o.OrderID == orderID
    from od in o.OrderDetails
    let total = od.Quantity * od.UnitPrice
    select new OrderDescription
    {
      Product = od.Product.ProductName,
      Quantity = od.Quantity,
      ShipperName = o.Shipper.CompanyName,
      Total = total,
      UnitPrice = od.UnitPrice,
      SupplierName = od.Product.Supplier.CompanyName
    };
  return orderDetails;
}


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

January 6. 2009 18:52