Joining and selecting only the first item based on clause

c# entity-framework-6

Accepted Answer

ZZZ_tmp
0
1/14/2019 1:52:35 PM

Popular Answer

I need to make some statistics for the first order of all new customers

var clientFirstOrders = db.Customers.Where(c => c.IsNew)
    .Select(c => new{
        Customer = c, 
        FirstOrder = c.Orders.OrderBy(c => c.OrderDate).FirstOrDefault()
    })
    // might have to do (int?)FirstOrder.Id != null or something like that.
    .Where(e => e.FirstOrder != null);

and count the number of first orders from new clients by month.

var clientCountByFirstOrderMonth = clientFirstOrders 
    .GroupBy(e => new { e.FirstOrder.OrderDate.Year, e.FirstOrder.OrderDate.Month })
    .Select(g => new{g.Key.Year, g.Key.Month, Count = g.Count()}); 


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow