Linq order by decimal field sorts like a string?

c#, linq

Solution

The C# Mongo DB driver serializes `decimal` as a string (The driver source-code corroborates this).

It does this because there is no BSON type for decimal - double does not have the same precision. 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.

Problem

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. 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. What am I missing here about decimals in C#? I am using the Mongo DB C# driver.

Original source

Related problems