简体   繁体   English

Linq 至 select 最新记录

[英]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:解释:

  1. Select rows for the specific ItemID特定 ItemID 的 Select 行
  2. Group by CurrencyID按 CurrencyID 分组
  3. From within each currency group select the row that has the most recent date (leaving one row for for each CurrencyID in the result set)来自每个货币组 select 具有最新日期的行(为结果集中的每个 CurrencyID 保留一行)
  4. Pull out the information you want from these rows从这些行中拉出你想要的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM