I'm trying to get a list of strings with numbers and characters sorted. The numbers can be units tens, thousands and tens of thousands (greater possibly also).
Here's an example of the strings:
1: abc
38: rst
203: pq
10371: mno
13: defg
1023: hi
109: jkl
For example from list
List<string> list = new List<string>()
{
"1: abc",
"38: rst",
"203: pq",
"10371: mno",
"13: defg",
"1023: hi",
"109: jkl",
};
My expected result would be
10371: mno
1023: hi
203: pq
109: jkl
38: rst
13: defg
1: abc
I've found this partial solution Sorting mixed numbers and strings
public class MixedNumbersAndStringsComparer : IComparer<string> {
public int Compare(string x, string y) {
double xVal, yVal;
if(double.TryParse(x, out xVal) && double.TryParse(y, out yVal))
return xVal.CompareTo(yVal);
else
return string.Compare(x, y);
}
}
list.Sort(new MixedNumbersAndStringsComparer());
But it sorts it like this instead of as expected above
1: abc
13: defg
109: jkl
1023: hi
10371: mno
203: pq
38: rst
How would you modify the MixedNumbersAndStringsComparer class to get it to sort it as expected? Thanks!