繁体   English   中英

Linq:group by不起作用

[英]Linq: group by doesn't work

我有一个让我的GROUP BY正常工作的问题。 有人能看出原因吗?

public void MonthlyTurnover(int year, int month) {
            var q1 = (from sp in _db.Species
                from p in _db.Pets
                from b in _db.Bookings.Where(x => x.ExpectedArrivalTime.Year == year &&
                    x.ExpectedArrivalTime.Month == month)
                where p.SpeciesId == sp.Id && b.PetId == p.Id && b.PetId == p.Id
                select new {sp.SpeicesName, Sum = b.Services.Sum(i => i.Price)}).ToList();

            foreach (var v in q1) {
                Console.WriteLine(v);
            }
}

我得到的没有分组

在此输入图像描述

public void MonthlyTurnover(int year, int month) {
            var q1 = (from sp in _db.Species
                from p in _db.Pets
                from b in _db.Bookings.Where(x => x.ExpectedArrivalTime.Year == year &&
                    x.ExpectedArrivalTime.Month == month)
                where p.SpeciesId == sp.Id && b.PetId == p.Id && b.PetId == p.Id
                select new {sp.SpeicesName, Sum = b.Services.Sum(i => i.Price)})
                .GroupBy(x => new{x.SpeicesName, x.Sum}).ToList();

            foreach (var v in q1) {
                Console.WriteLine(v.Key);
            }
}

我得到的是什么

在此输入图像描述

我想要什么......

在此输入图像描述

只按SpeicesName ,试试这个:

var q1 = (from sp in _db.Species
                from p in _db.Pets
                from b in _db.Bookings.Where(x => x.ExpectedArrivalTime.Year == year &&
                    x.ExpectedArrivalTime.Month == month)
                where p.SpeciesId == sp.Id && b.PetId == p.Id && b.PetId == p.Id
                select new {sp.SpeicesName, Sum = b.Services.Sum(i => i.Price)})
                .GroupBy(x => x.SpeicesName).Select(g=>new {SpeicesName=g.Key,Sum=g.Sum(e=>e.Sum)}).ToList();

不要按Sum ...分组,只按物种名称分组。

...
.GroupBy(x => x.SpeicesName).ToList();

现在你已经有了一系列的组,其中关键是物种名称。 您可以显示物种名称(一次),然后汇总所有个别总和。

foreach (var v in q1)
{
    Console.WriteLine("{0}: {1}", v.Key, v.Sum(x => x.Sum)); // "Dog: 7500", "Cat: 3500", etc
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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