使用 linq 按月和年排序

Orderby month and year using linq

我正在从数据库中获取不同的月份,但月份值采用月份和年份的形式。即,1 月 15 日,2 月 15 日。如何按月份和年份的升序获取它? 现在我得到的结果是:Apr-15 Feb-15 Jan-15 Mar-15。但我想要这样的结果:Jan-15 Feb-15 Mar-15 Apr-15.

 var months = ((from mnths in context.Table
                       orderby mnths.Month
                       select mnths.Month).Distinct()).ToList();

        return months;

谢谢。

您可以这样使用 DateTime.TryParseExact

var months = ((from mnths in context.Table
                   orderby mnths.Month
                   select mnths.Month).Distinct()).ToList().OrderBy(m =>
                   {
                        DateTime month;
                        return DateTime.TryParseExact(m, new[] {"MMM-yy"}, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out month)
                            ? month
                            : DateTime.MinValue;
                   }).ToList();

您需要在 OrderBy 之前调用 ToList 以便执行原始查询并且您得到 IEnumerable<string> 而不是 IQueryable

只需使用 .NET 排序方法。 首先从数据库中获取所有日期

var dates = ((from dts in context.Table
                         select dts).Distinct().ToList();

            return dates;

然后做

dates.Sort();
dates.Reverse();

你会得到你想要的结果。 (并将日期时间存储在 Db 中,日期时间类型不是 nvarchar 或其他)。