Sort by month in linq and EF

后端 未结 5 2032
傲寒
傲寒 2021-01-28 17:09

I have a linq query and inside of it is the month name. I want the results sorted by the month (Jan, Feb, Mar, ...).

Currently I have the below but it\'s giving me and e

5条回答
  •  北恋
    北恋 (楼主)
    2021-01-28 17:32

    You've got few options. You could use a long list of optional operators to map the names to numbers

    order by s.MonthName == "Jan" ? 1 : s.MonthName == "Feb" ? 2 : ...
    

    You could create a table in your DB that maps the names to nummeric values

    var shockValues = (from s in ctx.Shocks
                       join o in MonthOrder on s.MonthName equals o.MonthName
                       where s.ID == id
                       orderby o.MonthNumber
                       select new 
                       {
                           val = s.MonthName + "=" + s.ShockValue
                       });
    

    Or do the ordering in memory

    var shockValues = (from s in ctx.Shocks
                       where s.ID == id
                       select new
                              {
                                  s.MonthName,
                                  s.ShockValue
                              })
                      .AsEnumerable()
                      .OrderBy(s => DateTime.ParseExact(s.MonthName, "MMM", CultureInfo.InvariantCulture).Month)
                      .Select(s => new 
                                   {
                                       val = s.MonthName + "=" + s.ShockValue
                                   });
    

提交回复
热议问题