Linq to SQL get record with Max date value
If I was to write as follows...
var latest = _recor开发者_如何学JAVAds.OrderByDescending(x => x.Date).First();
Is this ordering the complete set? Or is Linq clever enough to work out that you're only looking for the max value? Is there a more efficient way of writing the above?
Yes, LINQ to SQL is smart enough to do the work on the database side. Your snippet will result in SQL like SELECT TOP (1) ... ORDER BY ...
.
(This is assuming that in your snippet _records
represents a System.Data.Linq.Table<T>
or something IQueryable
, etc.)
As far as the optimal way to write the query, you might consider FirstOrDefault()
if it's possible your table won't contain any records, in which case First()
will throw an exception.
精彩评论