rrgirish
rrgirish

Reputation: 331

Linq query for ordering by ascending order except for one row

I am pulling data from a table like the example below:

status_id   status_description
1             Unknown
2             Personal
3             Terminated
4             Relocated
6             Other
7             LOP
8             Continuing

I want to get the results into a IEnumerable which i am then returning to the front end to display the descriptions in a dropdown.

I want to sort this alphabetically and have the "Other" option always show up in the bottom of the dropdown.

Is there any way to get this in the backend? Currently I have this:

 IEnumerable<employee_map> map= await(from emp in db.emp_status_map
 orderby emp.status_description
 select emp).ToListAsync();

Upvotes: 0

Views: 331

Answers (2)

Servy
Servy

Reputation: 203827

Simply order on two values, first on whether the description is Other, then on the actual description itself:

orderby emp.status_description == "Other", emp.status_description

Upvotes: 2

Francisco Goldenstein
Francisco Goldenstein

Reputation: 13767

Servy's answer is fine, it works and fullfils your requirements. Another solution slightly different would be to add a field called "DisplayOrder", for example, and set it to 1 for all the rows except for "other", and set it to 2 (or whatever number you want) to "other". Then, you just order by DisplayOrder, Description.

It's highly probably that this solution is gonna be much faster if you define an index on DisplayOrder, Description.

Upvotes: 1

Related Questions