我想从表格中选择与众不同的年份 所以我写了代码:
return await _context.SdrSettingHistory
.Where( x => x.StartDate != null)
.OrderBy(x => x.StartDate)
.Select(x => x.StartDate.Value.Year)
.Distinct()
.ToListAsync();
但是它没有返回订购年份。它返回[2014,2015,2013] 我应该如何订购年份?
我试图在Distinct()之后移动OrderBy,它产生错误:
error CS1061: 'int' does not contain a definition for 'StartDate' and no accessible extension method 'StartDate' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
注意: 我将ASP.NET与EF Core 2.1一起使用
答案 0 :(得分:2)
不保证Select
和Distinct
运算符可以保留其他数据提供程序(例如SQL Server)上的顺序。您需要将OrderBy
运算符移到它们之后。由于Select
之后的预计值是int
,因此您可以直接按以下顺序进行排序:
return await _context.SdrSettingHistory
.Where(x => x.StartDate != null)
.Select(x => x.StartDate.Value.Year)
.Distinct()
.OrderBy(x => x)
.ToListAsync();