In a previous question I asked how I would get a Customers first Order, it was answered thus :
var minOrders = from customer in DataSet.Customers
let order = (from o in DataSet.Orders where o.CustomerId == customer.CustomerId
order by o.OrderTimestamp
select o).first()
select new {
customer.Name,
order.OrderAmount
});
This is great, but how do I include a Left Outer Join onto the above? That is, return all Customers even if they have no orders, so something like :
var minOrders = from customer in DataSet.Customers LEFT OUTER JOIN
let order = (from o in DataSet.Orders where o.CustomerId == customer.CustomerId
order by o.OrderTimestamp
select o).first()
select new {
customer.Name,
order.OrderAmount
});
I know, in hindsight I should of asked this at the same time..
Thanks, Joe
Firstly, using
letto do the join like this isn’t ideal in the first place. There’s ajoinclause in LINQ for a reason 🙂Left outer joins aren’t specifically supported in LINQ, but you can fake them like this:
Usually a left outer join uses
from foo in bar.DefaultIfEmptyinstead oflet foo = bar.FirstOrDefault()but in this case you’re only after the first match anyway, hence the different approach.I’m pretty sure this works logically – whether the SQL translation will work or not is a different matter.