You are here: Basics Operations & Concepts > Querying > SODA Query > Sorting by Field

SODA Sorting

You can specify to sort by certain fields in SODA. For this you need to descend to the field and use the appropriate order ascending or order descending method.

In cases where this is not enough, you can use a special comparator.

Sorting by Field

To sort by a field navigate to the field and call a order ascending or descending method. Note that this only works for fields which have natural sortable values, such as strings and numbers.

IQuery query = container.Query();
query.Constrain(typeof(Pilot));
query.Descend("name").OrderAscending();

IObjectSet result = query.Execute();
SodaSorting.cs: Order by a field
Dim query As IQuery = container.Query()
query.Constrain(GetType(Pilot))
query.Descend("name").OrderAscending()

Dim result As IObjectSet = query.Execute()
SodaSorting.vb: Order by a field

Sort by Multiple Fields

You can sort by multiple fields. Add a order constrain for each field. The first order statement has the highest priority and last added the lowest.

IQuery query = container.Query();
query.Constrain(typeof(Pilot));
query.Descend("age").OrderAscending();
query.Descend("name").OrderAscending();

IObjectSet result = query.Execute();
SodaSorting.cs: Order by multiple fields
Dim query As IQuery = container.Query()
query.Constrain(GetType(Pilot))
query.Descend("age").OrderAscending()
query.Descend("name").OrderAscending()

Dim result As IObjectSet = query.Execute()
SodaSorting.vb: Order by multiple fields

Sort With Your Own Comperator

In cases where you have more complex sorting requirements, you can specify your own comparator. It is used like a regular .NET-comparator.

IQuery query = container.Query();
query.Constrain(typeof(Pilot));
query.SortBy(new NameLengthComperator());

IObjectSet result = query.Execute();
SodaSorting.cs: Order by your comparator
Dim query As IQuery = container.Query()
query.Constrain(GetType(Pilot))
query.SortBy(New NameLengthComperator())

Dim result As IObjectSet = query.Execute()
SodaSorting.vb: Order by your comparator
class NameLengthComperator :IQueryComparator
{
    public int Compare(object first, object second)
    {
        Pilot p1 = (Pilot) first;
        Pilot p2 = (Pilot)second;
        // sort by string-length
        return Math.Sign(p1.Name.Length - p2.Name.Length);
    }
}
SodaSorting.cs: The string length comperator
Private Class NameLengthComperator
    Implements IQueryComparator
    Public Function Compare(ByVal first As Object, ByVal second As Object) As Integer _
        Implements IQueryComparator.Compare

        Dim p1 As Pilot = DirectCast(first, Pilot)
        Dim p2 As Pilot = DirectCast(second, Pilot)
        ' sort by string-length
        Return Math.Sign(p1.Name.Length - p2.Name.Length)
    End Function
End Class
SodaSorting.vb: The string length comperator