简体   繁体   English

按字母顺序排列列表,不包括字母

[英]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. 我正在尝试按字母顺序对列表进行排序(这很容易实现),但后来我希望以字母D开头的任何项目按照按字母顺序排序的列表进行排序。 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. 我确信我可以使用强力来处理这个问题,但是我希望有一种方法可以使用带有OrderBy().ThenBy() linq来实现它OrderBy().ThenBy()然后看看OrderBy().ThenBy()但是它看起来更像是在2个不同的属性上进行排序)。 Is what im trying to do possible with linq, or do I just have to do it the old fashioned way? 我试图用linq做什么,或者我只是必须用老式的方式做?

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: 要将名称以“D”开头的所有对象放在列表的末尾,只需使用:

.OrderBy(o => o.Name.StartsWith("D") ? 1 : 0)
.ThenBy(o => o.Name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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