如何获取其值最大的记录

发布于 2024-10-25 08:16:31 字数 95 浏览 1 评论 0原文

我有一个表包含一个具有日期数据类型的列。我想获取日期值最大的记录。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

羁客 2024-11-01 08:16:31

假设 Records 是对象的集合,并且要获取最大值的列/属性称为 value

var q = Records.OrderByDescending(p => p.value)
               .FirstOrDefault();

Assuming Records is a collection of your object and the column/property to get the max of is called value:

var q = Records.OrderByDescending(p => p.value)
               .FirstOrDefault();
水水月牙 2024-11-01 08:16:31

您可以按日期对集合进行排序并选择第一个:

List<Record> records = new List<Record>();
records.OrderByDescending(record => record.Date).First();

您可以使用 FirstOrDefault() 在集合为空时不引发异常(返回 null

You can order the collection by date and select the first one:

List<Record> records = new List<Record>();
records.OrderByDescending(record => record.Date).First();

You could use FirstOrDefault() to not throw an Exception when the collection is empty (null is returned)

秋风の叶未落 2024-11-01 08:16:31

不幸的是,LINQ 没有 MaxBy 运算符。您可能需要按适当的属性对项目进行降序排序,然后采用第一个值:

Customer lastRegistered = db.Customers.OrderByDescending(x => x.RegistrationDate)
                                      .FirstOrDefault();

希望 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:

Customer lastRegistered = db.Customers.OrderByDescending(x => x.RegistrationDate)
                                      .FirstOrDefault();

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.

春夜浅 2024-11-01 08:16:31

假设“记录”指的是底层数据库中表中的记录,该数据库可以有效地处理生成的 SQL(并支持最大聚合):

var q = 
    from t in thetable where t.Date == thetable.Max( d => d.Date ) select t;

这将找到与最大日期匹配的记录。 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):

var q = 
    from t in thetable where t.Date == thetable.Max( d => d.Date ) select t;

That would find records matching the maximum date. First() could be used to grab just one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文