Custom sorting logic in OrderBy using LINQ

What will be the correct way to sort the list of strings where I need elements starting with the underscore '_' at the bottom of the list, otherwise everything will be in alphabetical order.

Now I'm doing something like this,

autoList.OrderBy(a => a.StartsWith("_") ? "ZZZZZZ"+a : a ) 
+43
sorting c # linq sql-order-by
Jun. 09 '10 at 15:47
source share
3 answers

If you need a custom order but don’t want to ship it, you can get it - sql style:

 autoList .OrderBy(a => a.StartsWith("_") ? 2 : 1 ) .ThenBy(a => a); 
+86
Jun 09 '10 at 17:48
source share

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

+4
Jun 09 '10 at 15:53
source share

Use the IComparer overload, which takes IComparer , the first argument to Func will feed the comparator, and from there you need to compare the strings. First consider the case of one or both of the starts with _ , and then from there you probably need to pull down _ and just use the standard string.Compare to sort them outside the first _

+2
Jun 09 '10 at 15:55
source share



All Articles