I have an app that accesses database and has to order results by different fields depending on the input.
Here is my function for sorting:
IQueryable<Entity> GetSortedData(IQueryable<Entity> result, String orderby, bool desc)
{
switch (orderby.ToLower())
{
case "id":
result = result.OrderBy(c => c.Id);
break;
case "code":
result = result.OrderBy(c => c.Code);
break;
case "active":
result = result.OrderBy(c => c.Active);
break;
default:
result = result.OrderBy(c => c.Name);
break;
}
if (pageData.SortDesc)
{
var res = result.ToList();
res.Reverse();
return res.AsQueryable();
}
return result;
}
There are some problems with this code that I don't like:
Too much repetitive code. If it was "pure
SQL
" query, it would look likeSELECT * FROM data_table ORDER BY CASE @OrderBy WHEN 'id' THEN id WHEN 'code' THEN code
WHEN 'active' THEN active ELSE name
END ;Conversion to list and back for reversing. I can not change return type and I definitely do not want to write even more useless code (essentially doubling
switch
case
withOrderByDescending
).
Can anyone suggest ways of making this function better-looking, preferably still using LINQ
?