简体   繁体   English

LINQ顺序由十进制字段排序像一个字符串?

[英]Linq order by decimal field sorts like a string?

I'm totally baffled and cannot find anything on the internet about this, so I must be doing something wrong? 我完全困惑,无法在互联网上找到任何有关此的信息,所以我一定做错了什么?

 _positionsRepo.GetAllTrades().OrderByDescending(x => x.TotalPLPercent).ToList();

TotalPLPercent is a decimal field. TotalPLPercent是一个小数字段。 the result order sorts like this: 结果顺序如下所示:

96.76
95.54
8.54
75.55
231.22
13

Obviously, this is wrong. 显然,这是错误的。 I tested the sort against another field that was a double, and it worked as expected. 我在另一个为double的字段上测试了排序,它按预期工作。 What am I missing here about decimals in C#? 关于C#中的小数,我在这里缺少什么?

I am using the Mongo DB C# driver. 我正在使用Mongo DB C#驱动程序。

The C# Mongo DB driver serializes decimal as a string (The driver source-code corroborates this). C#Mongo DB驱动程序将decimal序列化为字符串驱动程序源代码证实了这一点)。

It does this because there is no BSON type for decimal - double does not have the same precision. 这样做是因为没有十进制的BSON类型-双精度没有相同的精度。 Unfortunately it means you can't compare "decimal" values as numbers. 不幸的是,这意味着您无法将“十进制”值作为数字进行比较。

You could sort the data in memory, like this: 您可以对内存中的数据进行排序,如下所示:

_positionsRepo.GetAllTrades()
   .ToList()
   .OrderByDescending(x => x.TotalPLPercent)
   .ToList();

Another option would be to store the number of cents (or hundredths of cents) as a long integer. 另一种选择是将美分(或百分之几美分)存储为长整数。 Then you can sort them normally, and you just have to divide by 100 (or 10,000) to get your real value. 然后,您可以按常规对它们进行排序,只需将其除以100(或10,000)即可获得实际价值。

Apparently, this is the problem with MongoDB Driver for C# . 显然,这是MongoDB Driver for C# Check this open issue here - 在这里检查此未解决的问题-

the 'System.Decimal' type save as 'String' 'System.Decimal'类型另存为'String'

As you can see since Decimal is saved as String , it surely will sort like a string. 如您所见,由于Decimal被保存为String ,因此它肯定会像字符串一样排序。 I think you should try double instead of decimal until they fix this issue. 我认为您应该尝试double而不是decimal直到他们解决此问题。

Are you sure the type of x is Decimal? 您确定x的类型为Decimal吗? It looks like it's doing a string ordering. 看起来它正在执行字符串排序。 (I'd put a breakpoint on "x.TotalPLPercent" and then evaluate x's type to double verify it's what I thought it was.) (我在“ x.TotalPLPercent”上设置了一个断点,然后评估x的类型以再次验证它是否是我的想法。)

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

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