我有以下代码
public class OrderDetails
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
}
public List<int> GetCustomerIds()
{
var orderDetails = new List<OrderDetails>
{
new OrderDetails {OrderId = 1001, CustomerId = 2001},
new OrderDetails {OrderId = 1001, CustomerId = 2002},
new OrderDetails {OrderId = 1002, CustomerId = 2003},
new OrderDetails {OrderId = 1002, CustomerId = 2002},
new OrderDetails {OrderId = 1003, CustomerId = 2003},
new OrderDetails {OrderId = 1003, CustomerId = 2002},
//return list of common customerIds.
};
}
我想获得所有订单中常见的CustomerIds
列表。在上面的示例中,我的输出将是2002
。实现这一目标的干净方法是什么?
答案 0 :(得分:6)
这将实现您的目标:
var result = orders.GroupBy(x => x.CustomerId)
.Where(y => y.Count() == orderDetails.GroupBy(z => z.OrderId)
.Count())
.FirstOrDefault()
.Key;
输出:
2002
我们可以用英语查询目的:
CustomerId
OrderId
分组并获取Count()
CustomerId
)重要提示:这只会占用第一位客户,以防有多个订单数量相同的订单,但更改此订单以获取所有订单都是微不足道的。
答案 1 :(得分:1)
首先查找订单总数,然后按客户对订单详细信息进行分组,最后选择订单数量与订单总数相同的客户。假设没有重复的客户订单对。
var numberOrders = orderDetails.Select(orderDetail => orderDetail.OrderId)
.Distinct()
.Count();
var result = orderDetails.GroupBy(orderDetail => orderDetail.CustomerId)
.Where(group => group.Count() == numberOrders)
.Select(group => group.Key)
.ToList();