使用 LINQ 在 OrderBy 中自定义排序逻辑 [英] Custom sort logic in OrderBy using LINQ
本文介绍了使用 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);
这篇关于使用 LINQ 在 OrderBy 中自定义排序逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文