Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding common elements within a list of objects

Tags:

c#

linq

c#-4.0

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?

like image 235
user1527762 Avatar asked Mar 19 '23 14:03

user1527762


1 Answers

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:

  • Group your collection on the CustomerId
  • Gather how many different orders there are by grouping on OrderId and getting the Count()
  • Filter the collection to those customers which appear as often as there are orders
  • Select the first
  • Print the key (which is the 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.

like image 138
Jeroen Vannevel Avatar answered Mar 31 '23 11:03

Jeroen Vannevel