2014-02-24 81 views
0

我有一個CarID,ServiceType,ServiceDate,MilesLastService表。 我想檢索特定ServiceType的特定汽車的最後一條記錄的ServiceDate和MilesLastService。 linq查詢將如何查看。Linq多個聚合和最大

在我的腦海查詢看起來是這樣的:

Max(select ServiceDate, MilesLastService 
Where (CarID = 50 && ServiceType == "TransmissionService") 

我是想這樣的事情,但我不能弄清楚

var d2 = from m in db.Table<ServiceRecords>() 
where m.CarID == carid 
group m by new { m.ServiceDate, m.Milage }; 

有人能幫忙嗎?

回答

0

下面的查詢將選擇最後一條記錄對於給定的車每個服務類型:

from sr in db.Table<ServiceRecords>() 
where sr.CarID == id 
group sr by sr.ServiceType into g 
select g.OrderByDescending(sr => sr.ServiceDate).First(); 

如果你想只得到英里和日期,然後

from sr in db.Table<ServiceRecords>() 
where sr.CarID == id 
group sr by sr.ServiceType into g 
let lastRecord = g.OrderByDescending(sr => sr.ServiceDate).First() 
select new { 
    lastRecord.MilesLastService, 
    lastRecord.ServiceDate 
} 
0

可以使用LINQ像下面:

var d2 = (from m in db.Table<ServiceRecords>() 
      where m.CarID == carid && m.ServiceType == "TransmissionService" 
      select new {ServiceDate = m.ServiceDate, MilesLastService = m.MilesLastService}) 
     .OrderBy(x => x.ServiceDate) 
     .Last(); 
var milesLastService = d2.MilesLastService; 
var serviceDate = d2.ServiceDate; 

我已經使用ServiceDate訂購了檢索列表。