简体   繁体   中英

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.

How can I only get the customers with orders?

Use 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM