Linq按问题排序

时间:2016-10-27 17:56:09

标签: c# linq

我尝试按包含日期时间值的VARCHAR2字段订购结果集。它们是从GoToWebinar获得的,我无法将它们转换为DateTime

9/29/2016 6:00:00 PM
8/31/16 5:48 PM
9/28/16 5:58 PM
9/14/16 5:57 PM
9/1/16 5:57 PM
9/21/16 5:52 PM
9/22/16 5:59 PM
9/15/16 5:59 PM
9/7/16 5:56 PM
9/8/16 5:55 PM

我需要像这样正确排序:

8/31/16 5:48 PM
9/1/16 5:57 PM
9/7/16 5:56 PM
9/8/16 5:55 PM
9/14/16 5:57 PM
9/15/16 5:59 PM
9/21/16 5:52 PM
9/22/16 5:59 PM
9/28/16 5:58 PM
9/29/2016 6:00:00 PM

尝试这样做:

using (webinarAttendeesListDbContext context = new webinarAttendeesListDbContext(connectionString))
{
    System.Linq.IQueryable<WebinarAttendeesList> result = null;
        result = from w in context.WebinarAttendeesList
                 where webinarkeys.Contains(w.webinarKey) && w.AttendedWebinar > 0
                 orderby w.PID, DateTime.Parse(w.JoinTime)
                 select w;
    r = result.ToList();
}

我收到此错误:

  

LINQ to Entities无法识别方法&#39; System.DateTime   解析(System.String)&#39;方法,这个方法无法翻译   进入商店表达。

我如何需要按此顺序执行此操作?

1 个答案:

答案 0 :(得分:2)

  1. 使用ToList()检索数据,然后对其进行排序:

    using (webinarAttendeesListDbContext context = new webinarAttendeesListDbContext(connectionString))
    {
        var result = (from w in context.WebinarAttendeesList
                      where webinarkeys.Contains(w.webinarKey) && w.AttendedWebinar > 0
                      select w).ToList()
                               .OrderBy(w => w.PID)
                               .ThenBy(w => DateTime.Parse(w.JoinTime));
    }
    
  2. 另一种选择是使用DbFunctions.CreateDateTime 功能

  3. 您也可以使用this answer
  4. 中的SqlFunctions.DateAdd