Alan Alan - 1 month ago 8
C# Question

Is there a way I could change a LINQ query orderBy depending on a parameter?

I coded two LINQ statements with different orderBy. Is there a way that I could change the orderBy without having to code twice like this:

if (param == "s")
{
var result = await db.PhraseCategories
.OrderBy(p => p.SortOrder)
.Select(p => new
{
Id = p.PhraseCategoryShortId,
Name = p.Name
})
.AsNoTracking()
.ToListAsync();
return Ok(result);
}

if (param == "n")
{
var result = await db.PhraseCategories
.OrderBy(p => p.Name)
.Select(p => new
{
Id = p.PhraseCategoryShortId,
Name = p.Name
})
.AsNoTracking()
.ToListAsync();
return Ok(result);
}

Answer

Other option can be to work on query like:

IQueryable<PhraseCategory> query = db.PhraseCategories;

// Order as needed
if(param == "s")
    query = query.OrderBy(m => m.SortOrder);
else if(param == "n")
    query = query.OrderBy(m => m.Name);

var result = await query
    .Select(p => new
    {
     Id = p.PhraseCategoryShortId,
     Name = p.Name
    })
    .AsNoTracking()
    .ToListAsync();     
return Ok(result);

Additionally, if you can get param in the form of property name to order according to, then you can write extension method to dynamically order according to property name as shown in this answer.