簡體   English   中英

Linq 內部加入組,然后選擇組,為什么有空組?

[英]Linq inner join into group, then selecting group, why are there empty groups?

我正在嘗試獲取包含各自訂單的客戶列表,但如果客戶沒有任何訂單,則應將其排除在該列表之外。

        var customerOrders = (from customer in customers
            join order in orders on customer.CustomerId equals order.CustomerId into
                orderGroup
            select new
            {
                Customer.CustomerId,
                Orders = orderGroup.ToList()
            }).ToList();

在 customerOrders 列表中,我收到沒有訂單或訂單列表為空的客戶。

我怎樣才能只得到有訂單的客戶?

使用where orderGroup.Any()

var customerOrders =
(
    from customer in customers
    join order in orders on customer.CustomerId equals order.CustomerId into orderGroup
    where orderGroup.Any()
    select new
    {
        customer.CustomerId,
        Orders = orderGroup.ToList()
    }
).ToList();

或者group order by customer.CustomerId into g

var customerOrders =
(
    from customer in customers
    join order in orders on customer.CustomerId equals order.CustomerId
    group order by customer.CustomerId into g
    select new
    {
        CustomerId = g.k,
        Orders = g.ToList()
    }
).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM