Sort by month in linq and EF

后端 未结 5 2033
傲寒
傲寒 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:15

    The best way and easiest way is create a stored procedure

    Create procedure sortevents
       as
     SELECT *
            FROM [SAGMJ].[dbo].[Events]
            ORDER BY CASE 
                     WHEN MONTH([StartAt]) = MONTH(GETDATE())
                        AND YEAR([StartAt])  = YEAR(GETDATE()) THEN 0
                       ELSE 1
                     END, [StartAt];
    

    //Next call your sp

    var v = (dc.sortevents()).ToList();
    
    0 讨论(0)
  • 2021-01-28 17:22

    Something like this should work

    var shockValues = ctx.Shocks.Where(s => s.ID == id).Select(x => new {x.MonthName, MonthNum = x.MonthName == "Jan" : 1 ? x.MonthName == "Feb" : 2 ? 0}).OrderBy(s => MonthNum).Select(s => new {val = s.MonthName + "=" + s.ShockValue}     
    
    0 讨论(0)
  • 2021-01-28 17:23

    If you dont want to create a table in your database, you can do like

    var names = DateTimeFormatInfo.CurrentInfo.MonthNames
                .Take(12).Select(s => new[] {s.Substring(0,3)});
    

    And then order against a separate list.

    orderby names.IndexOf(s.MonthName)
    
    0 讨论(0)
  • 2021-01-28 17:31

    Try:

    orderby Convert.ToDateTime(s.MonthName + " 1, " + DateTime.Now.Year.ToString()).Month
    
    0 讨论(0)
  • 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
                                   });
    
    0 讨论(0)
提交回复
热议问题