'Fetch Unique List of Items from Related property Entity Framework

I am having 2 entities Customer and Orders and they are related

customer 
---------
CustomerId
name

Order 
---------

OrderId
OrderDate
CustomerId

I want to fetch a specific no of unique customers based on some specific scenarios or conditions and sort based on the Order Date.

Ended up with this entity framework query

IQueryable<Order> query = context.Orders;

//build various conditions 
query = query.where()....

List<Order> OrdersList = new List<Order>();

OrdersList =  query.
                OrderByDescending(s=>s.OrderDate).
                Take(20).
                ToList();
            
//prepare unique list of contact IDS & Subscription IDs associated with current selection
List<int> Customers = OrdersList.GroupBy(s => s.CustomerId)
                            .Select(grp => grp.First().CustomerId)
                            .ToList();      
                            

This is returning the last 20 orders to me and from this there might not be 20 unique customers always. If a given customer got multiple orders then this list is less than 20.

But how can i fetch the 20 unique customers based on the Order Date
[The customers who did some recent purhchases ?]



Solution 1:[1]

You say you need customers, so why not start with customers? Assume you're using EntityFramework.

Pseudocode?

  var topCustomers = customers.Include(c=>c.Orders)
      .OrderbyDescending(c=>c.Orders.Max(o=>o.OrderDate))
      .Take(20)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1