且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在linq和EF中按月排序

更新时间:2023-01-29 20:39:07

您别无选择.您可以使用一长串可选的运算符将名称映射到数字

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
                   });

或者在内存中进行排序

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
                               });