如何获取其值最大的记录
我有一个表包含一个具有日期数据类型的列。我想获取日期值最大的记录。
Linq 支持 Max,但它返回值本身。我想要其值最大的记录。
任何帮助!
I have a table contains a column with Date datatype. I want to get the record which its date value is the maximum.
Linq supports Max
, but it returns the value itself. I want the record which its value is the maximum.
Any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设
Records
是对象的集合,并且要获取最大值的列/属性称为value
:Assuming
Records
is a collection of your object and the column/property to get the max of is calledvalue
:您可以按日期对集合进行排序并选择第一个:
您可以使用
FirstOrDefault()
在集合为空时不引发异常(返回null
)You can order the collection by date and select the first one:
You could use
FirstOrDefault()
to not throw an Exception when the collection is empty (null
is returned)不幸的是,LINQ 没有 MaxBy 运算符。您可能需要按适当的属性对项目进行降序排序,然后采用第一个值:
希望 SQL Server 能够弄清楚如何做到这一点,而无需真正进行完整排序:)
在 LINQ to Objects 中,它是当然,编写
MaxBy
方法相对容易 - 我已经在 MoreLINQ 中找到了例子。Unfortunately LINQ doesn't have a
MaxBy
operator. You probably need to order your items descending by the appropriate property, and then take the first value:Hopefully SQL Server can work out how to do that without really doing a full sort :)
In LINQ to Objects it's relatively easy to write a
MaxBy
method of course - I've got on in MoreLINQ for example.假设“记录”指的是底层数据库中表中的记录,该数据库可以有效地处理生成的 SQL(并支持最大聚合):
这将找到与最大日期匹配的记录。
First()
可用于仅获取一个。Assuming "record" is referring to a record from a table in an underlying database that can handle the resulting SQL efficiently (and supports the max aggregate):
That would find records matching the maximum date.
First()
could be used to grab just one.