3

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?

AndroidLearner
  • 4,500
  • 4
  • 31
  • 62
Subby
  • 5,370
  • 15
  • 70
  • 125

1 Answers1

8

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).

nickvane
  • 2,979
  • 2
  • 20
  • 23
  • 1
    Yes, but at least in the code he posted, there is no index name specified. If RavenDB is generating the temporary index dynamically, then it will add the sort order automatically. But perhaps it is matching on a predefined index that is missing it, so you get my +1. :) – Matt Johnson-Pint Jun 05 '13 at 16:00
  • @MattJohnson Is there a way to specify the sortoptions when not using a static index? – nickvane Jun 06 '13 at 10:08
  • 1
    If Raven matches your query to an existing index, it will use the sort order in that index. If it dynamically creates one for you, it will create correct sort order based on the type of your data. So if you `OrderBy` an integer in your query, and raven creates a temp index for you, it will include the integer sort order in that index. – Matt Johnson-Pint Jun 10 '13 at 01:58