Home > front end >  LINQ Conditional OrderBy
LINQ Conditional OrderBy

Time:01-31

I'm trying to do a conditional OrderBy but it's having no effect. The List outputs the same with default ordering.

I've tried both approaches suggested in this question 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();

CodePudding user response:

LINQ methods do not mutate the query object, they return new one, you need to reassign it:

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

....
  • Related