2

I have searched around and been unable to find anything on this, maybe I'm not sure how to phrase my question correctly for Google.

I need to sort a list of strings alphabetically, while handling strings that contain more than one letter.

Given the values "A", "AA", "B", "BB", "C", "Z", "CC"

I need the output to be "A", "B", "C", "Z", "AA", "BB", "CC"

I've looked into natural sorting, but that doesn't give me the desired results.

2
  • 5
    Make it simple, sort on length first, then alphabetically. list.OrderBy(s => s.Length).ThenBy(s => s) Commented Jan 22, 2019 at 14:59
  • order it by lenght and value Commented Jan 22, 2019 at 14:59

1 Answer 1

4

Following should help you

var list = new []{"A", "AA", "B", "BB", "C", "Z", "CC"};
var result = list.OrderBy(x => x.Length).ThenBy(x=> x);

The key to solution lies in Ordering the List by Length of each entry,and Then By actual value.

Output

A 
B 
C 
Z 
AA 
BB 
CC 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I was overthinking it. Will accept as answer when I can.
Answers which explain how the code presented works generally get more upvotes than those without.
@HereticMonkey was typing the explanation :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.