我对LINQ相对较新,但是对SQL本身很精通。我有一个查询,试图在其中加入2个表-一个表是汽车列表,另一个表是每个表的测试记录。我想出了如何加入最新测试的方法,但没有获得特定于此的评论字段。
所以可以说测试数据是:
CarID |TestDriveDate |Comments
========+=======================+===========
1 |1/7/2019 |ok
2 |12/7/2019 |average
2 |10/7/2019 |poor
2 |15/7/2019 |good
使用以下代码:
var query = from test in TestDrives
group test by test.CarID into g
join car in Cars
on g.Key equals car.CarID
select new TestViewModel
{
CarID = g.Key,
CarName = car.CarName
Model = car.Model
LastTestDrive = g.Max(a => a.TestDriveDate),
//and the comment field where its the max inspection date
Comments = g.Select(a => a.Comments).FirstOrDefault()
};
因此应返回以下记录:
CarID |TestDriveDate |Comments
========+=======================+===========
2 |15/7/2019 |good
答案 0 :(得分:1)
您不需要更改Group
,只需添加Sort
。
Comments = g.Select(a => a.Comments).Sort((test1, test2)=>test1.TestDriveDate.CompareTo(test2.TestDriveDate)).FirstOrDefault();
或将orderby
添加到select
。
var query = from test in TestDrives
orderby test.TestDriveDate
group test by test.CarID into g
join car in Cars
on g.Key equals car.CarID