我有下面的查询,从列表中提取一个项目。
latestDoc = openDocs.Where(d => d.docBatchId == HARD_CODED_ID).FirstOrDefault();
我也想找到行与latestStatusDate…我使用的是MAX函数,但它返回null,因为我相信MAX是在寻找所有文档的最大值,我只想让它找到包含这个batchId
的文档的最大值latestDoc = openDocs.Where(d => d.docBatchId == HARD_CODED_ID && d.prodStatus == openDocs.Max(d => d.ProdStatus)).FirstOrDefault();
任何想法?
助教,瑜珈
您可以使用OrderByDescending
:
latestDoc = openDocs.Where(d => d.docBatchId == HARD_CODED_ID)
.OrderByDescending(d => d.StatusDate)
.FirstOrDefault();
我相信像这样的东西会得到你想要的
var latestDoc = openDocs.Where(d => d.docBatchId == HARD_CODED_ID)
.OrderByDescending(d => d.ProdStatus)
.FirstOrDefault();
下面的c#在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();
结果是03/01/2014 00:00:00 (3rd January 2014),这是docBatchId为123的3个条目的最新状态日期。