Linq Query in UiPath

Given a collection of orders where each order contains an OrderId, CustomerId, OrderDate, and a collection of OrderItems (with ProductId, Quantity, and Price), write a LINQ query to return the top 3 customers by total order value in the last 6 months. The result should include CustomerId and the total amount spent

Hi @VISHAL_TIWARI
Welcome to Community

You can try this

var sixMonthsAgo = DateTime.Now.AddMonths(-6);

var topCustomers = orders
.Where(order => order.OrderDate >= sixMonthsAgo)
.GroupBy(order => order.CustomerId)
.Select(group => new
{
CustomerId = group.Key,
TotalSpent = group.Sum(order =>
order.OrderItems.Sum(item => item.Quantity * item.Price))
})
.OrderByDescending(x => x.TotalSpent)
.Take(3)
.ToList();

Cheers

Hi @VISHAL_TIWARI,

Try this

orders.Where(Function(o) o.OrderDate >= Now.AddMonths(-6)).
GroupBy(Function(o) o.CustomerId).
Select(Function(g) New With {
.CustomerId = g.Key,
.TotalAmount = g.Sum(Function(o) o.OrderItems.Sum(Function(i) i.Quantity * i.Price))
}).
OrderByDescending(Function(x) x.TotalAmount).
Take(3).
ToList()

1 Like

Can you share a sample/screenshot of your data, so that it is more clear.
Will help on linq design accordingly.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.