linq 基于嵌套筛选器计算总和

b4lqfgs4  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(157)

“问题是”
这将按预期工作,并生成totalpax字段正确的结果。但是,每个目标的pax字段应该是基于目标ID的总和。

代码

public async Task<IEnumerable<ReservationCalendarGroupVM>> GetForCalendarAsync(string fromDate, string toDate) {
        return await context.Schedules
            .AsNoTracking()
            .Where(x => x.Date >= Convert.ToDateTime(fromDate) && x.Date <= Convert.ToDateTime(toDate))
            .GroupBy(z => new { z.Date })
            .Select(e => new ReservationCalendarGroupVM {
                Date = e.Key.Date.ToString(),
                Destinations = e.GroupBy(i => new { i.Destination.Id, i.Destination.Abbreviation, i.Destination.Description }).Select(p => new DestinationCalendarVM {
                    Id = p.Key.Id,
                    Abbreviation = p.Key.Abbreviation,
                    Description = p.Key.Description,
                    Pax = context.Reservations.Where(y => y.Date == e.Key.Date).Sum(h => h.TotalPersons)
                }),
                TotalPax = context.Reservations.Where(y => y.Date == e.Key.Date).Sum(h => h.TotalPersons).ToListAsync();
    }

结果

"date": "2022-07-02",
"destinations": [
    {
        "id": 1,
        "description": "PAXOS - ANTIPAXOS",
        "abbreviation": "PA",
        "pax": 254
    },
    {
        "id": 3,
        "description": "BLUE LAGOON",
        "abbreviation": "BL",
        "pax": 254
    }
],
"totalpax": 432
jdzmm42g

jdzmm42g1#

我相信问题就在于这一行:

Pax = context.Reservations.Where(y => y.Date == e.Key.Date).Sum(h => h.TotalPersons)

您只按日期过滤,但同时需要按目的地过滤。由于您没有共享模型,因此不太容易推断,但我认为您需要执行以下操作:

Pax = context.Reservations
    .Where(y => y.Date == e.Key.Date && y.Destination.Id == e.Key.Id).Sum(h => h.TotalPersons)

相关问题