linq查询,将sql查询转换为linq for VB.net

时间:2012-03-08 23:06:04

标签: linq

我试图从一个表中获取字段,从另一个表中获取max(expirationDate)。这是我原来的linq查询:

                            tanks = (From t In db.Table1 _
                            Where t.CompanyID = txtCompanyID.Text.Trim() _
                            Join d In db.Table2 On t.TankID Equals d.TankID
                            Order By d.ExpireDate Descending
                            Select t).ToList

带回多个expireDates,我只想要每个记录的max(expireDate)

以下sql查询有效,我只需将其放入linq查询

    select t1.*,
(Select MAX(Table2.ExpireDate) 
from Table2 as t2 
where t2.TankID = t1.TankID) 
as max_expire_date
      from Table1 as t1 
      where t1.CompanyID = '5467'
      order by t1.CargoTankID

有谁知道怎么把它变成linq?感谢

1 个答案:

答案 0 :(得分:0)

tanks = db.Table1.Where( t => t.CompanyId == txtCompanyID.Text.Trim() )
                 .Join( db.Table2, t1 => t1.TankID, t2 => t2.TankID, (t1,t2) => new { Company = t1, t2.ExpireDate } )
                 .GroupBy( t => t.Company, (c,e) => new { Company = c Expiration = e.Max( x => x.ExpireDate ) } )
                 .ToList();

最佳猜测VB

Dim tanks = db.Table1.Where( Function(t) t.CompanyId == txtCompanyID.Text.Trim() ) _
                     .Join( db.Table2, Function(t1) t1.TankID, Function(t2) t2.TankID, Function(t1,t2) New Thing With { .Company = t1, .ExpireDate = t2.ExpireDate } ) _
                     .GroupBy( Function(t) t.Company, Function(c,e) New Thing With { .Company = c, .Expiration = e.Max( Function(x) x.ExpireDate ) } ) _
                     .ToList()