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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With