I have an SQL Server Reporting Services (SSRS) report that is using SQL order by
sorting and returns the following for alphanumeric string data:
Value: 0.0
Value: 20.96
Value: 289.64
Value: 30.99
Value: 308.655
Value: -32296.32
Value: 34.844
Value: 38.95
Value: -697.38
Value: -703.48
Each string has the following format:
`Value: numeric data`
The SQL order by
seems to sort as a string but ignores the minus sign before the numeric values.
I am using C# with LINQ to sort the strings to try to match that sorting:
var _sorted = _unsortedValues.OrderBy(x => x.Description);
I get:
Value: -32296.32
Value: -697.38
Value: -703.48
Value: 0.0
Value: 20.96
Value: 289.64
Value: 30.99
Value: 308.655
Value: 34.844
Value: 38.95
LINQ by default sorts the stings with all the minus values first ascending, followed by zero and then positive values
Any ideas on how to get the desired sorting to replicate SSRS sorting?
NOTE
I have other types of string in this report column that are sorted correctly. e.g.
"Timestamp: data time data"
"Identifier: string data"
I suppose by LINQ here you mean regular LINQ to objects, not Entity Framework or LINQ to sql. How strings are sorted depends on comparer used, and you can pass whichever comparer you like to the OrderBy
statement. So for example to get the sorting you want, you may do this:
var sorted = _unsortedValues.OrderBy(x => x.Description, StringComparer.InvariantCulture).ToArray();
Which will return the same order as your SQL statement.
At the same time if you will use another comparer, like this:
var sorted = _unsortedValues.OrderBy(x => x.Description, StringComparer.Ordinal).ToArray();
You will get the order like in your question (negative numbers first).
Why you get the order you get, but other people cannot reproduce that? That's because by default, CurrentCulture
string comparer is used, and current culture might be different for different machines, so people get different results.
var sorted = _unsortedValues.OrderBy(x => x.Description, StringComparer.CurrentCulture).ToArray(); // this is what is done by default