Given a ordered list:
var lst = new []{"1","10","2","b","ab"};
var lst2 = lst.OrderBy(c => c);
Result of lst2
:
1, 10, 2, ab, b
Why does String.Compare()
not also measure on the length of the string when it compares?
I would have thought that the result would be more like this:
1, 2, 10, b, ab
Because 10 (something(1) and somthing(0)) should be after 2 (something(2) and nothing)
Could anybody give a good reason for this?
A string is a set of characters.
When comparing strings, it basically is a set comparision, i.e., the first character of both strings are compared. Only if they are the same are the next characters compared etc.
When correctly aligning your list of unordered strings by their first character, this becomes obvious:
"1"
"10"
"2"
"b"
"ab"
After ordering, the result will be:
"1"
"10"
"2"
"ab"
"b"
Reasons:
"2"
will come after "1"
, because '2'
> '1'
. "2"
will come after "10"
, because, again, '2'
> '1'
. The '0'
in "10"
is not taken into account, because the comparison of the first characters already results in an unambiguous result. "ab"
will come after "2"
, because 'a'
> '2'
"b"
will come after "ab"
, because 'b'
> 'a'
. The 'b'
in "ab"
is not taken into account, because the comparison of the first characters already results in an unambiguous result.If you want have the numbers in the strings ordered the way you want, you may want to look into "Natural Sort".
The ordering of your strings makes no sense, so you probably would have to build that yourself.