简体   繁体   中英

Linq complex object groupBy

I have fairly simple structure:
Each Customer has his WeeklyOrder .
WeeklyOrder consists of 5 DailyOrders and
in each DailyOrder are 5 OrderItems with ItemType (one of 5 slots basically) and Count .

I want to get counts for this week. So I get all DailyOrders from all users for this week.

var orders = db
    .WeeklyOrders
    .Where(x => x.WeekNumber == week && x.Year == year)
    .SelectMany(x => x.DailyOrders);

Everything works fine, but now i don't know how to group daily orders by DailyOrder.DayNumber and how to group items in each DailyOrder (not all together, for each daily order separately) so i know the sum from all users - how many items of type 1 were ordered for Monday how many for Tuesday etc.

I am asking only for the correct linq query.

To give you and idea of what I want to get in my view:

Monday

  • Item1: x1
  • Item2: y1
  • Item3: z1
  • Item4: u1
  • Item5: v1

Tuesday

  • Item1: x2
  • Item2: y2
  • Item3: z2
  • Item4: u2
  • Item5: v2

...
etc.

Here is my model:

public class WeeklyOrder
{
    public int WeeklyOrderId { get; set; }
    public int UserId { get; set; }
    public int Year { get; set; }
    public int WeekNumber { get; set; }

    public virtual Customer Customer { get; set; }
    public virtual List<DailyOrder> DailyOrders { get; set; }
}

public class DailyOrder
{
    public int DailyOrderId { get; set; }
    public int DayNumber { get; set; }
    public int WeeklyOrderId { get; set; }

    public virtual WeeklyOrder WeeklyOrder { get; set; }
    public virtual List<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
    public int OrderItemId { get; set; }
    public int Count { get; set; }
    public int ItemTypeId { get; set; }
    public int DailyOrderId { get; set; }

    public virtual DailyOrder DailyOrder { get; set; }
    public virtual ItemType Type { get; set; }
}

Try this:

var orders = db
    .WeeklyOrders
    .Where(x => x.WeekNumber == week && x.Year == year)
    .SelectMany(x => x.DailyOrders.SelectMany(y => y.OrderItems))
    .GroupBy(a => new
    {
        DayNumber = a.DailyOrder.DayNumber,
        Type = a.Type
    })
    .Select(a => new
    {
        DayNumber = a.Key.DayNumber,
        Type = a.Key.Type,
        Total = a.Sum(b => b.Count)
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM