英文:
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<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.
答案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 => x.MyMaxDate)
.Select(d => d.MyMaxDate).FirstOrDefault();
Generated query
SELECT TOP(1) [m].[MyMaxDate]
FROM [MyMaxDateClass] AS [m] ORDER BY [m].[MyMaxDate] DESC
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论