简体   繁体   中英

Sort a list alphabetically excluding a letter

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM