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?
CodePudding user response:
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();