2015-05-29 102 views
3

我有一个让GROUP BY正常工作的问题。有人能看到为什么吗?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

回答

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

谢谢,那正是我需要:) – user3389475

+0

不客气,很高兴为你提供帮助;) – octavioccl

2

不要按总和分组......只按物种名称分组。

... 
.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 
} 
+0

谢谢,这是我需要什么:) – user3389475

+0

不客气。 :) –