简体   繁体   English

对包含浮点数的字符串列表进行排序

[英]Sort a list of strings which contains float numbers

I have a list of object which contains a field Number.我有一个包含字段编号的 object 列表。 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.该字段是一个包含浮点数的字符串: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.我希望这个列表根据这个数字排序(后代)所以我有这个 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 ):另外,我曾尝试像这样使用 PadLeft(因为该用户建议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.但在这两种情况下,我都得到了错误的结果,例如: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?你知道如何解决这个问题吗?

The question arises why you have a string in the first place if you store a double .问题出现了,如果存储double ,为什么首先要有一个string 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 .如果您不知道它们是否具有所有有效格式,您可以使用double.TryParse Maybe you need to pass the appropriate CultureInfo to double.Parse (for example if your current culture uses comma as decimal separator).也许您需要将适当的CultureInfo传递给double.Parse (例如,如果您当前的文化使用逗号作为小数分隔符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM