【问题标题】:Linq query for sorting by date, then by status, then by nameLinq 查询按日期排序,然后按状态排序,然后按名称排序
【发布时间】:2013-07-03 11:30:36
【问题描述】:

代码:

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

我使用上面的代码对 日期 进行了排序,它工作很好。我需要在日期排序后添加另外两个条件,即按状态按名称

【问题讨论】:

  • 您是否使用ThenBy 而不是OrderBy 用于第一个以外的其他项目?
  • 不,我没有使用ThenBy。如果可能,更改上面的代码并作为答案发布。

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


【解决方案1】:

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;

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      我想你需要的是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)
          : ... ;
      

      【讨论】:

        猜你喜欢
        • 2021-09-30
        • 2018-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        • 2023-03-14
        • 1970-01-01
        • 2013-01-14
        相关资源
        最近更新 更多