Linq Sub-Select

Dan picture Dan · Feb 9, 2009 · Viewed 41.4k times · Source

How do I write a sub-select in LINQ.

If I have a list of customers and a list of orders I want all the customers that have no orders.

This is my pseudo code attempt:

    var  res = from c in customers 
where c.CustomerID ! in (from o in orders select o.CustomerID) 
select c

Answer

Jon Skeet picture Jon Skeet · Feb 9, 2009

How about:

var res = from c in customers 
          where !orders.Select(o => o.CustomerID).Contains(c.CustomerID)
          select c;

Another option is to use:

var res = from c in customers
          join o in orders 
               on c.CustomerID equals o.customerID 
               into customerOrders
          where customerOrders.Count() == 0
          select c;

Are you using LINQ to SQL or something else, btw? Different flavours may have different "best" ways of doing it