Possible Duplicate:
Natural Sort Order in C#
I have a list with a lot of numbers in it. But they are saved as strings because of some additional letters.
My list looks something like this:
1
10
11
11a
11b
12
2
20
21a
21c
A1
A2
...
but it should look like this
1
2
10
11a
11b
...
A1
A2
...
How do i sort my list to get this result?
Going by the previous comments, I would also implement a custom IComparer<T>
class. From what I can gather, the structure of the items is either a number, of a combination of a number followed by a letter(s). If this is the case, the following IComparer<T>
implementation should work.
public class CustomComparer : IComparer<string>
{
public int Compare(string x, string y)
{
var regex = new Regex("^(d+)");
// run the regex on both strings
var xRegexResult = regex.Match(x);
var yRegexResult = regex.Match(y);
// check if they are both numbers
if (xRegexResult.Success && yRegexResult.Success)
{
return int.Parse(xRegexResult.Groups[1].Value).CompareTo(int.Parse(yRegexResult.Groups[1].Value));
}
// otherwise return as string comparison
return x.CompareTo(y);
}
}
With this IComparer<T>
, you'll be able to sort your list of string
by doing
var myComparer = new CustomComparer();
myListOfStrings.Sort(myComparer);
This has been tested with the following items:
2, 1, 4d, 4e, 4c, 4a, 4b, A1, 20, B2, A2, a3, 5, 6, 4f, 1a
and gives the result:
1, 1a, 2, 20, 4a, 4b, 4c, 4d, 4e, 4f, 5, 6, A1, A2, a3, B2