Custom sort logic in OrderBy using LINQ

China☆狼群 提交于 2019-11-26 09:34:30

问题


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 )

回答1:


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);



回答2:


I think you need to use OrderBy(Func<>, IComparer<>) and specify your own Comparer which will implement your custom logic .




回答3:


Use the overload of OrderBy that takes an IComparer, the first Func argument will feed the comparer, and from there you need to compare the strings. First deal with the case of one or both starts with _, and then from there you will probably need to strip the _ and just use the standard string.Compare to sort them beyond the first _



来源:https://stackoverflow.com/questions/3007470/custom-sort-logic-in-orderby-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!