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 )
3 个解决方案
#1
91
If you want custom ordering, but don't want to supply a comparer, you can have it - sql style:
如果你想要自定义排序,但又不想提供比较器,你可以拥有它--sql风格:
autoList
.OrderBy(a => a.StartsWith("_") ? 2 : 1 )
.ThenBy(a => a);
#2
5
I think you need to use OrderBy(Func<>, IComparer<>)
and specify your own Comparer
which will implement your custom logic .
我认为您需要使用OrderBy(Func <>,IComparer <>)并指定您自己的Comparer,它将实现您的自定义逻辑。
#3
2
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 _
使用带有IComparer的OrderBy的重载,第一个Func参数将提供比较器,并从那里你需要比较字符串。首先处理一个或两个的情况以_开头,然后从那里你可能需要剥离_并且只使用标准字符串。比较它们超出第一个_
#1
91
If you want custom ordering, but don't want to supply a comparer, you can have it - sql style:
如果你想要自定义排序,但又不想提供比较器,你可以拥有它--sql风格:
autoList
.OrderBy(a => a.StartsWith("_") ? 2 : 1 )
.ThenBy(a => a);
#2
5
I think you need to use OrderBy(Func<>, IComparer<>)
and specify your own Comparer
which will implement your custom logic .
我认为您需要使用OrderBy(Func <>,IComparer <>)并指定您自己的Comparer,它将实现您的自定义逻辑。
#3
2
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 _
使用带有IComparer的OrderBy的重载,第一个Func参数将提供比较器,并从那里你需要比较字符串。首先处理一个或两个的情况以_开头,然后从那里你可能需要剥离_并且只使用标准字符串。比较它们超出第一个_