3

I have a good way to sort data "naturally" with an IComparer similar to the answers @ Natural Sort Order in C#. In my case, I have a class that goes something like this:

public class Widget
{
    public int Id { get; set; }
    public string Name { get; set; }
}

If I have a collection that reads as follows,

[{Id: 1, Name: "2 N. Street"},{Id: 2, Name: "33 N. Street"},{Id: 3, Name: "4 N. Street"}]

using an OData query like the following would return the data in the same order as above,

http://www.example.com/Widget.svc/GetWidgets?$orderby=Name

while I actually would like the data "naturally" ordered as such:

[{Id: 1, Name: "2 N. Street"},{Id: 3, Name: "4 N. Street"},{Id: 2, Name: "33 N. Street"}]

Is there a good way to customize a WCF service to make any query that tries to order by any string property to sort data "naturally"?

Community
  • 1
  • 1
Peter Majeed
  • 5,304
  • 2
  • 32
  • 57
  • The best way to generally handle this that I've found is to provide an implementation of `IQueryable` that naturally sorts string columns. I'll provide an answer that spells this out in more detail if I can get to it. – Peter Majeed Apr 29 '17 at 02:00

1 Answers1

0

This is now possible via a pre-release NuGet package called Buildium.ComparedQueryable.

Install-Package Buildium.ComparedQueryable -Version 0.1.3

Given you have an IQueryable stored in memory, calling AsNaturalQueryable on it would return the collection sorted naturally.

using ComparedQueryable;

public IHttpActionResult Get()
{
    IEnumerable<Widget> widgets = this.service.GetWidgets();
    return widgets.AsNaturalQueryable();
}
Peter Majeed
  • 5,304
  • 2
  • 32
  • 57