I have the following code
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.
};
}
I want to get a list of CustomerIds
that are common across all orders. In the example above my output would be 2002
. What is a clean way of achieving this?
This will accomplish what you want:
var result = orders.GroupBy(x => x.CustomerId)
.Where(y => y.Count() == orderDetails.GroupBy(z => z.OrderId)
.Count())
.FirstOrDefault()
.Key;
Output:
2002
We can read the purpose from the query in English:
CustomerId
OrderId
and getting the Count()
CustomerId
)Important note: this will only take the first customer in case there are multiple with the same amount of orders, but changing this to take them all is trivial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With