Search for common items in the list of objects

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 CustomerIdsthat is common to all orders. In the above example, my output will be 2002. What is the clean way to achieve this?

+4
source share
2 answers

This will do what you want:

var result = orders.GroupBy(x => x.CustomerId)
                   .Where(y => y.Count() == orderDetails.GroupBy(z => z.OrderId)
                                                        .Count())
                   .FirstOrDefault()
                   .Key;

Conclusion:

2002

We can read the target from the request in English:

  • Group your collection on CustomerId
  • Collect how many different orders exist, grouping by OrderIdand receivingCount()
  • Filter the collection for those customers who appear as often as there are orders
  • Pick first
  • Print the key (this CustomerId)

: , , .

+6

, , , , . .

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

Source: https://habr.com/ru/post/1540621/


All Articles