Reputation: 61
I have the folowing query that pulls an item from a list.
latestDoc = openDocs.Where(d => d.docBatchId == HARD_CODED_ID).FirstOrDefault();
I want to also find the row with the latestStatusDate...I'm using the MAX function but it returns null, as I believe Max is looking for the max of all the docs, I simply want it to find the max of the docs that contain this batchId
latestDoc = openDocs.Where(d => d.docBatchId == HARD_CODED_ID && d.prodStatus == openDocs.Max(d => d.ProdStatus)).FirstOrDefault();
Any ideas?
Ta, yogi
Upvotes: 0
Views: 56
Reputation: 3659
The following c# compiles and runs in LinqPad...
var openDocs = new [] {
new {
docBatchId = 123,
StatusDate = new DateTime(2014, 01, 01)
},
new {
docBatchId = 123,
StatusDate = new DateTime(2014, 01, 02)
},
new {
docBatchId = 123,
StatusDate = new DateTime(2014, 01, 03)
}
,
new {
docBatchId = 456,
StatusDate = new DateTime(2014, 01, 04)
}
};
var HARD_CODED_ID = 123;
var latestDoc = (from doc in openDocs
where doc.docBatchId == HARD_CODED_ID
select doc.StatusDate).Max();
latestDoc.Dump();
The result is 03/01/2014 00:00:00 (3rd January 2014), which is the latest statusDate for the 3 items with a docBatchId of 123.
Upvotes: 0
Reputation: 7288
I believe something like this will get you what you are looking for
var latestDoc = openDocs.Where(d => d.docBatchId == HARD_CODED_ID)
.OrderByDescending(d => d.ProdStatus)
.FirstOrDefault();
Upvotes: 0
Reputation: 460068
You can use OrderByDescending
:
latestDoc = openDocs.Where(d => d.docBatchId == HARD_CODED_ID)
.OrderByDescending(d => d.StatusDate)
.FirstOrDefault();
Upvotes: 1