使用 LINQ 在 OrderBy 中自定义排序逻辑
问题描述:
对字符串列表进行排序的正确方法是什么,我希望以下划线_"开头的项目位于列表底部,否则一切都按字母顺序排列.
What would be the right way to sort a list of strings where I want items starting with an underscore '_', to be at the bottom of the list, otherwise everything is alphabetical.
现在我正在做这样的事情,
Right now I'm doing something like this,
autoList.OrderBy(a => a.StartsWith("_") ? "ZZZZZZ"+a : a )
答
如果你想要自定义排序,但又不想提供比较器,你可以拥有它 - sql style:
If you want custom ordering, but don't want to supply a comparer, you can have it - sql style:
autoList
.OrderBy(a => a.StartsWith("_") ? 2 : 1 )
.ThenBy(a => a);