Linq Sub-Select

后端 未结 4 1388
-上瘾入骨i
-上瘾入骨i 2020-12-16 15:31

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

4条回答
  •  清酒与你
    2020-12-16 15:44

    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

提交回复
热议问题