Linq Sub-Select

后端 未结 4 1373
-上瘾入骨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 16:04

    If this is database-backed, try using navigation properties (if you have them defined):

    var res = from c in customers
              where !c.Orders.Any()
              select c;
    

    On Northwind, this generates the TSQL:

    SELECT /* columns snipped */
    FROM [dbo].[Customers] AS [t0]
    WHERE NOT (EXISTS(
        SELECT NULL AS [EMPTY]
        FROM [dbo].[Orders] AS [t1]
        WHERE [t1].[CustomerID] = [t0].[CustomerID]
        ))
    

    Which does the job quite well.

提交回复
热议问题