3
votes

In my C# application, I have a collection of objects which have an int Order property ranging from 1 to n.

When I do like this:

var listings = session.Query<Listing>().Where(x => !x.IsDeleted && x.CategoryId == category.Id && x.WorkflowStatus == WorkflowStatus.Published).OrderBy(x => x.Order);

I get a collection of listings but not 100% in the correct order. As it stands the order goes:

0, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 28, 29, 3, 30, 31, 32, 33, 4 .... 

Any idea why the OrderBy doesn't do exactly as it should?

1
Looks like it has them as strings for some reason - Colm Prunty
What has what as strings? - Subby
It's considering the Order property to be a string instead of an int, that's how it would be ordered if they were text. - Colm Prunty
ah yes I see what you mean. Any idea how to fix this issue? - Subby
You could try OrderBy(x => (int)x.Order); but I'm not sure why it's returning as string if it's supposed to be stored as an int. - Colm Prunty

1 Answers

8
votes

If you are using an index you need to set the sortoptions for the Order property. From http://ravendb.net/docs/client-api/querying/static-indexes/customizing-results-order

Numerical values, on the other hand, are stored as text and therefore require the user to specify explicitly what is the number type used so a correct sorting mechanism is enforced. This is quite easily done, by declaring the required sorting setup in SortOptions in the index definition:

Sort(x => x.Order, SortOptions.Int);

The index outlined above will allow sorting by value on the user's age (1, 2, 3, 11, etc). If we wouldn't specify this option, it would have been sorted lexically (1, 11, 2, 3, etc). The default SortOptions value is String. Appropriate values available for all numeric types (Byte, Double, Float, Int, Long and Short).