Search code examples
c#linq

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

enter image description here

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


Solution

  • 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 => x.MyMaxDate)
                                   .Select(d => d.MyMaxDate).FirstOrDefault();
    
    

    Generated query

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