Reputation: 23871
I have a table contains a column with Date datatype. I want to get the record which its date value is the maximum.
Linq supports Max
, but it returns the value itself. I want the record which its value is the maximum.
Any help!
Upvotes: 0
Views: 116
Reputation: 41262
Assuming "record" is referring to a record from a table in an underlying database that can handle the resulting SQL efficiently (and supports the max aggregate):
var q =
from t in thetable where t.Date == thetable.Max( d => d.Date ) select t;
That would find records matching the maximum date. First()
could be used to grab just one.
Upvotes: 0
Reputation: 18832
Assuming Records
is a collection of your object and the column/property to get the max of is called value
:
var q = Records.OrderByDescending(p => p.value)
.FirstOrDefault();
Upvotes: 6
Reputation: 3250
You can order the collection by date and select the first one:
List<Record> records = new List<Record>();
records.OrderByDescending(record => record.Date).First();
You could use FirstOrDefault()
to not throw an Exception when the collection is empty (null
is returned)
Upvotes: 2
Reputation: 1503924
Unfortunately LINQ doesn't have a MaxBy
operator. You probably need to order your items descending by the appropriate property, and then take the first value:
Customer lastRegistered = db.Customers.OrderByDescending(x => x.RegistrationDate)
.FirstOrDefault();
Hopefully SQL Server can work out how to do that without really doing a full sort :)
In LINQ to Objects it's relatively easy to write a MaxBy
method of course - I've got on in MoreLINQ for example.
Upvotes: 1