Search code examples
c#linqclassdistinctminimum

Finding Minimum 3 Distinct Items From Array of Objects Using LINQ in C#


I have a class Customer that holds an array of class Order.

    class Customer
    {
        public string firstname { get; set; }
        public string lastname { get; set; }

        public Order[] orders {get; set;}
    }

This is my order class:

     class Order
{
    public string product { get; set; }
    public float price{get; set;}
    public int quantity { get; set; }
}

I am trying to find the three least expensive products.

I have tried many things but none seem to work. This is what I have at the moment:

    var result = customer.SelectMany(x => x.orders);
    var  Least = result.Distinct().OrderBy(x => x.price).Take(3);

I realized I need to have distinct as I have many orders with the same product name therefore instead of returning the least three expensive products it was just repeating the least expensive product 3 times.


Solution

  • Distinct() will not work here because it is selecting distinct Order objects. In layman's terms, this means that customer A's order of 3 staplers at $9.99 each is different from customer B's order of 2 staplers at $9.99 each, which are also both different from customer C's order of 3 staplers at $9.99 each. So in essence your call to Distinct() is actually doing nothing.

    You have a couple of options. You can create an IEqualityComparer which will consider Orders of the same product equal, or you can use GroupBy() instead:

    var query = myListOfCustomers.SelectMany(x => x.Orders)
                    .GroupBy(x => new { x.Product, x.Price })
                    .Select(x => x.Key)
                    .OrderBy(x => x.Price)
                    .Take(3);
    

    Note this treats Orders having the name product name but a different price as a different product. It also assumes Order.Price is the unit price. I do not know if either of these assumptions are correct.