Linq查询按日期排序,然后按状态排序,然后按名称排序

时间:2013-07-03 11:30:36

标签: linq c#-4.0 asp.net-mvc-4 iqueryable

代码:

IQueryable<Task> taskRecord = parentId != Guid.Empty ? _taskReadService.GetRecords()
                             .Where(x => x.TaskId == taskId).OrderBy(x => x.Date)

我使用上面的代码对日期进行了排序,它正在运行精细。在日期排序后,我需要添加另一个两个条件,即按状态按名称

3 个答案:

答案 0 :(得分:0)

正如 Caramiriel 建议使用ThenBy

IQueryable<Task> taskRecord = parentId != Guid.Empty ? _taskReadService.GetRecords()
                             .Where(x => x.TaskId == taskId)
                             .OrderBy(x => x.Date)
                             .ThenBy(x => x.Status)
                             .ThenBy(x => x.Name) : null;

答案 1 :(得分:0)

为了便于阅读,我会稍微格式化代码....

IQueryable<Task> taskRecord = null;
if(parentId != Guid.Empty)
{
     taskRecord = _taskReadService.GetRecords()
                                  .Where(x => x.TaskId == taskId)
                                  .OrderBy(x => x.Date)
                                  .ThenBy(x => x.Status)
                                  .ThenBy(x => x.Name);
}

答案 2 :(得分:0)

我认为你需要的是ThenBy。添加第二个OrderBy会重置排序顺序(实际执行排序,然后再求助一次)。通过推断示例:

IQueryable<Task> taskRecord =
    parentId != Guid.Empty
    ? _taskReadService.GetRecords()
        .Where(x => x.TaskId == taskId)
        .OrderBy(x => x.Date)
        .ThenBy(x => x.Status)
        .ThenBy(x => x.Name)
    : ... ;