I'm relatively new to LINQ but well versed in SQL itself. I have a query where I'm trying to join 2 tables - one a list of cars and the other a record of test drives on each. I figured how to join with the most recent test but am not getting the comments field specific to that.
So lets say that the tests data are:
CarID |TestDriveDate |Comments
========+=======================+===========
1 |1/7/2019 |ok
2 |12/7/2019 |average
2 |10/7/2019 |poor
2 |15/7/2019 |good
With the following code:
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()
};
So the following record should be returned:
CarID |TestDriveDate |Comments
========+=======================+===========
2 |15/7/2019 |good
You don't need to change your Group
, you need to add a Sort
.
Comments = g.Select(a => a.Comments).Sort((test1, test2)=>test1.TestDriveDate.CompareTo(test2.TestDriveDate)).FirstOrDefault();
Or add the orderby
to the 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.