gpt4 book ai didi

c# - Entity Framework 查询最大

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:03 26 4
gpt4 key购买 nike

有人让我把T-SQL语句转换成LINQ to EF查询:

SELECT * FROM  CopperPrices  
where ID in
(select max(ID) as ID from copperprices group by market, pname)

我使用常见的 LINQ-TO-OBJECT 思想并给出以下答案:

class CopperPrice
{
public int ID { get; set; }
public string Market { get; set; }
public string PName { get; set; }
}

var result = from p in copperPrices
group p by new { Market = p.Market, PName = p.PName } into g
select g.OrderByDescending(p => p.ID).First();

但由于以下异常,它在 EF 中不起作用:

The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead

能否将上述T-SQL语句转换为一条LINQ查询语句?

最佳答案

给你:

var result1 = copperPrices.GroupBy(g => new { g.Market, g.PName }).Select
(
x => x.ToList().OrderByDescending(z => z.ID).FirstOrDefault()
);

这里的重要部分是 .Select(x => x.ToList())。 ToList 返回一个 IGrouping 的值,每个值都是您最终要排序并选择最大值的值。

关于c# - Entity Framework 查询最大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11533760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com