Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom sort logic in OrderBy using LINQ

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 )
like image 484
Bala R Avatar asked Jun 09 '10 15:06

Bala R


3 Answers

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);
like image 111
Amy B Avatar answered Nov 06 '22 01:11

Amy B


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

like image 37
abatishchev Avatar answered Nov 06 '22 01:11

abatishchev


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 _

like image 2
Matt Greer Avatar answered Nov 06 '22 01:11

Matt Greer