Linq order by not working on DateTime after group by into anonymous object

问题描述 投票:0回答:1

注意:ThisDate 可以为空。 尝试获取这样排序的下拉列表的字符串列表:

2023 March
2023 February 
2023 January 

等等

我的查询:

ThisDateList = await ctx.Table1
    .OrderByDescending(i => i.ThisDate)
    .GroupBy(i => new { i.ThisDate.Value.Year, i.ThisDate.Value.Month})
    .Select(g => g.Key.Year.ToString() + " " + DateTimeFormatInfo.InvariantInfo.GetMonthName(g.Key.Month))
    .Distinct()
    .ToListAsync();

但是他们没有按照我预期的方式得到命令。谢谢。

c# linq .net-core entity-framework-core linq-to-entities
1个回答
0
投票

尝试以下查询:

ThisDateList = await ctx.Table1
    .Select(i => new { i.ThisDate.Value.Year, i.ThisDate.Value.Month })
    .Distinct()
    .OrderByDescending(x => x.Year)
    .ThenByDescending(x => x.Month)
    .Select(x => x.Year.ToString() + " " + DateTimeFormatInfo.InvariantInfo.GetMonthName(x.Month))
    .ToListAsync();
© www.soinside.com 2019 - 2024. All rights reserved.