2015-05-29 94 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

不客氣。 :) –