[英]Linq to select latest records
I have the data structure我有数据结构
For each item there is a record of it's price on a certain date in each currency.对于每件商品,都有其在特定日期以每种货币表示的价格记录。 I need to create a query that returns the most current price for each currency.我需要创建一个查询来返回每种货币的最新价格。
This query works, but returns multiple Amounts
for currency ID 1
.此查询有效,但返回货币 ID 1
的多个Amounts
。 It should only return 3 records, 7,8 and 9
as these represent the most up to date prices in all currencies for this item.它应该只返回 3 条记录, 7,8 and 9
,因为这些代表该项目所有货币的最新价格。
var q = (from c in db.tblStoreItemPrices where c.ItemID == ID select new { c.CurrencyID, c.Amount });
Please ignore all ordering and assume that records are randomly ordered.请忽略所有排序并假设记录是随机排序的。
This should work:这应该工作:
db.tblStoreItemPrices
.Where(c => c.ItemID == ID)
.GroupBy(c => c.CurrencyID)
.Select(g => g.OrderByDescending(c => c.Date).First())
.Select(c => new { c.CurrencyID, c.Amount });
Explanation:解释:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.