C# Linq 选择最新记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10026772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:10:54  来源:igfitidea点击:

Linq to select latest records

c#linq

提问by Tom Gullen

I have the data structure

我有数据结构

enter image description here

在此处输入图片说明

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 Amountsfor currency ID 1. It should only return 3 records, 7,8 and 9as these represent the most up to date prices in all currencies for this item.

此查询有效,但Amounts为货币 ID返回多个1。它应该只返回 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.

请忽略所有排序并假设记录是随机排序的。

Thanks for any help!

谢谢你的帮助!

采纳答案by Jon

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
  2. Group by 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)
  4. Pull out the information you want from these rows
  1. 为特定的 ItemID 选择行
  2. 按货币 ID 分组
  3. 从每个货币组中选择具有最新日期的行(为结果集中的每个 CurrencyID 留一行)
  4. 从这些行中拉出你想要的信息