50

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

3 Answers 3

103

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);
1
  • 4
    I like this solution better. I always forget about ThenBy.
    – Matt Greer
    Jun 9, 2010 at 19:28
6

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

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 _

1
  • 1
    However, in all honesty, although technically your approach is a hack and can fail, it's a lot simpler and easier to understand your intent.
    – Matt Greer
    Jun 9, 2010 at 15:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.