返回最大日期到属性

huangapple go评论61阅读模式
英文:

Return Max Date to a property

问题

I am trying to get the last date from a table in a database. Please see the logic I have tried below but with no success.

Here is my class with a DateTime Property.

public class MyMaxDateClass
{
    public DateTime? MyMaxDate { get; set; }
}

Here is the task where I am using LINQ to return the max date. To assign back to the property.

public async Task<MyMaxDateClass> GetMyMaxDateClassDateAsync()
{
    MyMaxDateClass myMaxDateClass = new();

    myMaxDateClass = await (from s in _databaseDbContext.MyTable
                            select s.DateColumn).MaxBy();

    return myMaxDateClass;
}

Please logic pasted above

返回最大日期到属性

If I had these 2 dates, I'd expect it to return the latest one.

英文:

I am trying to get the last date from a table in a database. Please see the logic I have tried below but with no success.

Here is my class with a DateTime Property.

public class MyMaxDateClass
{
    public DateTime? MyMaxDate{ get; set; }
}

Here is the task where I am using LINQ to return the max date. To assign back to the property.

public async Task&lt;MyMaxDateClass&gt; GetMyMaxDateClassDateAsync()
{
    MyMaxDateClass myMaxDateClass = new();

    myMaxDateClass = await (from s in _databaseDbContext.MyTable
                        select s.DateColumn).MaxBy();

    return myMaxDateClass;
}

Please logic pasted above

返回最大日期到属性

If I had these 2 dates I'd expect it to return the latest one.

答案1

得分: 1

你可以使用 max 和 OrderByDescending。

max

var myMaxDateClass = (from s in context.MyMaxDateClass select s.MyMaxDate).Max();

生成的查询

SELECT MAX([m].[MyMaxDate]) FROM [MyMaxDateClass] AS [m]

OrderByDescending

var S = context.MyMaxDateClass.OrderByDescending(x => x.MyMaxDate)
                               .Select(d => d.MyMaxDate).FirstOrDefault();

生成的查询

SELECT TOP(1) [m].[MyMaxDate] 
FROM [MyMaxDateClass] AS [m] ORDER BY [m].[MyMaxDate] DESC
英文:

you can use max and OrderByDescending

max

var myMaxDateClass = (from s in context.MyMaxDateClass select s.MyMaxDate).Max();

Generated query

SELECT MAX([m].[MyMaxDate]) FROM [MyMaxDateClass] AS [m]

OrderByDescending

 var S = context.MyMaxDateClass.OrderByDescending(x =&gt; x.MyMaxDate)
                               .Select(d =&gt; d.MyMaxDate).FirstOrDefault();

Generated query

SELECT TOP(1) [m].[MyMaxDate] 
FROM [MyMaxDateClass] AS [m] ORDER BY [m].[MyMaxDate] DESC

huangapple
  • 本文由 发表于 2023年8月5日 00:00:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定