简体   繁体   English

Linq 内部加入组,然后选择组,为什么有空组?

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

I'm trying to get a list of customers with their respective orders, but if a customer doesn't have any orders they should be excluded from this list.我正在尝试获取包含各自订单的客户列表,但如果客户没有任何订单,则应将其排除在该列表之外。

        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();

In the customerOrders list, I'm getting customers with no orders or with empty Orders list.在 customerOrders 列表中,我收到没有订单或订单列表为空的客户。

How can I only get the customers with orders?我怎样才能只得到有订单的客户?

Use where orderGroup.Any() :使用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();

Or group order by customer.CustomerId into g :或者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