Reputation: 572
I have a list of object which contains a field Number. This field is a string that includes float numbers: 0.5, 0.2, 10.0, 2.2, 2.1, 1.1, 1.0, 2.12, 1.14. I want this list sorted (descendent) based on this Number so I have this output: 10.0, 2.2, 2.12, 2.1, 1.14, 1.1, 1.0, 0.5, 0.2.
I have tried to do this:
List<MyObject> sortedList = myUnsortedList.OrderyDescending(x => x.Number).ToList();
Also, I have tried to use PadLeft like this (as this user suggested https://stackoverflow.com/a/6396523/3872144):
int maxlen = myUnsortedList.Max(x => x.Number.Length);
List<MyObject> sortedList = myUnsortedList.OrderyDescending(x => x.Number.PadLeft(maxlen, '0'));
But in both cases I got wrong results like: 2.12, 10.0, 2.2, 2.1, 1.14, 1.1, 1.0, 0.5, 0.2.
Do you have any idea how to solve this issue?
Upvotes: 0
Views: 411
Reputation: 460238
The question arises why you have a string
in the first place if you store a double
. You should parse them as soon as possible (or prevent that they are strings where you load them).
However, you can always try to parse them afterwards:
List<MyObject> sortedList = myUnsortedList
.OrderyDescending(x => double.Parse(x.Number))
.ToList();
If you dont know if they have all a valid format you can use double.TryParse
. Maybe you need to pass the appropriate CultureInfo
to double.Parse
(for example if your current culture uses comma as decimal separator).
Upvotes: 5