.net LINQ条件排序依据

8xiog9wr  于 2023-01-31  发布在  .NET
关注(0)|答案(1)|浏览(112)

我尝试做一个条件OrderBy,但是没有效果。List输出的是相同的默认排序。
我尝试了这个问题中建议的两种方法Conditional "orderby" sort order in LINQ

var query =  _context.Groups
        .Where(gr => gr.Status != ((sbyte)ActiveStatus.DELETED) 
                    && gr.OrganisationId == user.OrganisationId 
                    && (search != null && gr.Name != null ? (gr.Name.Contains(search)) : true == true)
                    )
        .Select(GroupReportModel.Projection);

        if(!pager.Sort.HasValue || pager.Sort.Value == ((int)Sort.MODIFIED))
            query.OrderByDescending(gr => gr.Created.Date);

        if(pager.Sort.Value == ((int)Sort.NAME))    
            query.OrderByDescending(gr => gr.Name);
    
    
    pager.TotalRecords = query.Count(); 
    var list = query.Skip(pager.PageCount != null ? pager.PageCount.Value * (pager.Page.Value) : 0)
        .Take(pager.PageCount != null ? pager.PageCount.Value  : 0)
        .ToList();
xfb7svmp

xfb7svmp1#

LINQ方法不会改变查询对象,它们返回一个新的查询对象,您需要重新分配它:

if(!pager.Sort.HasValue || pager.Sort.Value == ((int)Sort.MODIFIED))
    query = query.OrderByDescending(gr => gr.Created.Date);

if(pager.Sort.Value == ((int)Sort.NAME))    
    query = query.OrderByDescending(gr => gr.Name);

....

相关问题