Linq:小组并没有工作

时间:2015-05-29 13:25:50

标签: c# linq

我在让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);
            }
}

没有小组我得到的

enter image description here

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);
            }
}

我通过

获得的内容

enter image description here

和我想要的......

enter image description here

2 个答案:

答案 0 :(得分:3)

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();

答案 1 :(得分:2)

不要按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
}