B
Bill McCormick
How would you structure a Linq statement using Max to return the record with
the greatest (newest) datetime field?
the greatest (newest) datetime field?
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
How would you structure a Linq statement using Max to return the record with
the greatest (newest) datetime field?
How would you structure a Linq statement using Max to return the
record with the greatest (newest) datetime field?
Because I like to be fancyBill McCormick wrote on 29-6-2009 :
Why not sort it (descending, so that the newest date is on top) and then
take the first?
That, and I'd like to learn how these things work.Try:
http://msdn.microsoft.com/en-us/vbasic/bb737922.aspx
They are in VB, but it is fairly straighforward to convert, as boht use
extension methods.
Bill said:Thanks. I just found the exact same page before I saw your post and it
was helpful. Here's what I did:
var ctare = (from t in TTares
where (t.TTareDateTime) == (from r in TTares
select r.TTareDateTime).Max()
select t.TTareWeight).Single<double>();
It might be more efficient to compute the maximum only once outside of
the where predicate e.g.
DateTime latest = (from r in TTares select r.TTareDateTime).Max();
var ctare = (from t in TTares
where t.TTareDateTime == latest
select t.TTareWeight).Single<double>();
Have learned that the other alteratives aren't as good, I've come around toBecause I like to be fancyThat, and I'd like to learn how these
things work.
Strange, if I compare the two syntaxes, the TOP 1 is about twice slower
than the subquery. With the batch (show execution plan):
SELECT TOP 1 * FROM ParamsProjetDefauts ORDER BY TimeStampRef DESC;
SELECT * FROM ParamsProjetDefauts WHERE TimeStampRef = (SELECT
MAX(TimeStampRef) FROM ParamsProjetDefauts);
the first query, accordingly to the query execution plan, take 68% of
the time to run the whole batch (while the subquery takes only 32 % of
the batch time). The solution you adopted is (probably) translated to
the TOP 1, case.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.