Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list alphabetically excluding a letter

Tags:

c#

sorting

linq

I have a list of objects each with a name. I'm trying to sort the list in alphabetical order (which is easily accomplished) but then I want any item beginning with the letter D to be sorted following the alphabetically sorted list. so given the items:

(Apple, Door, Banana, Doorknob, Gorilla, Hammer)  

I would like to sort this as :

(Apple, Banana, Gorilla, Hammer, Door, Doorknob) 

I'm sure I could handle this using brute force, but I was hoping there was a way to do it with linq with OrderBy().ThenBy() but it looks like thats more for sorting on 2 different properties. Is what im trying to do possible with linq, or do I just have to do it the old fashioned way?

like image 427
user1336827 Avatar asked Dec 26 '22 02:12

user1336827


1 Answers

You can use any expression that returns a sortable value as a sort order; it doesn't have to be a property. To put all objects whose name starts with "D" at the end of the list just use:

.OrderBy(o => o.Name.StartsWith("D") ? 1 : 0)
.ThenBy(o => o.Name)
like image 140
D Stanley Avatar answered Dec 27 '22 16:12

D Stanley