Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have following data in my list and I want to sort it in following order.

entries are like below,

List<String> codeb = new List<string>();
           codeb.Add("CH-01-0223,B");
           codeb.Add("CH-01-0220,A");
           codeb.Add("AL-01-0023,B");
           codeb.Add("AL-01-0200,A");
           codeb.Add("AL-02-0101,B");
           codeb.Add("AL-02-0201,A");


I want result like below,

AL-01-0200,A
AL-01-0023,B
AL-02-0201,A
AL-02-0101,B
CH-01-0220,A
CH-01-0223,B


What I have tried:

I tried using
C#
codeb.sort()


but it gives sorting like below,
AL-01-0023,B
AL-01-0200,A
AL-02-0101,B
AL-02-0201,A
CH-01-0220,A
CH-01-0223,B
Posted
Updated 3-Sep-18 1:41am
v2
Comments
Patrice T 3-Sep-18 7:30am    
Show a single piece of code that build the list, sort and display result.

1 solution

You can't just used a "standard string sort" and expect it to give you results that aren't in standard string order - and string ordering is based on comparing each character in turn from the left to the right and the whole comparison being based on the first different character.

You need to provide a custom sort method and call it from OrderBy:
var sorted = codeb.OrderBy(s => s, Comparer<string>.Create((l, r) => MySortMethod(l, r)));

Your method will look like this:
private int MySortMethod(string l, string r)
    {
    ...
    }
And returns -1 if l is less than r, 0 if they are the same, and 1 if l is greater than r.

Since I have no idea why your required sort order is the way it is you will have to write that bit yourself!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900