Sorting Query Results

Often applications need to present query results in a sorted order. There are several ways to achieve this with db4o.

This Pilot class will be used in the following examples:

Pilot.cs
01/* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com */ 02namespace Db4objects.Db4odoc.Sorting 03{ 04 class Pilot 05 { 06 private string _name; 07 private int _points; 08 09 public Pilot(string name) 10 { 11 _name = name; 12 } 13 14 public Pilot(string name, int points) 15 { 16 _name = name; 17 _points = points; 18 } 19 20 public string Name 21 { 22 get 23 { 24 return _name; 25 } 26 } 27 28 public int Points 29 { 30 get 31 { 32 return _points; 33 } 34 } 35 36 public override string ToString() 37 { 38 if (_points == 0) 39 { 40 return _name; 41 } 42 else 43 { 44 return string.Format("{0}/{1}", _name, _points); 45 } 46 } 47 } 48}

Pilot.vb
01' Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com 02 03Namespace Db4objects.Db4odoc.Sorting 04 Class Pilot 05 Private _name As String 06 Private _points As Integer 07 08 Public Sub New(ByVal name As String) 09 Me._name = name 10 End Sub 11 12 Public Sub New(ByVal name As String, ByVal points As Integer) 13 Me._name = name 14 Me._points = points 15 End Sub 16 17 Public ReadOnly Property Name() As String 18 Get 19 Return _name 20 End Get 21 End Property 22 23 Public ReadOnly Property Points() As Integer 24 Get 25 Return _points 26 End Get 27 End Property 28 29 Public Overloads Overrides Function ToString() As String 30 If _points = 0 Then 31 Return _name 32 Else 33 Return String.Format("{0}/{1}", _name, _points) 34 End If 35 End Function 36 End Class 37End Namespace

The database will be filled with the following Pilot objects:

SortingExample.cs: SetObjects
01private static void SetObjects() 02 { 03 File.Delete(Db4oFileName); 04 IObjectContainer db = Db4oFactory.OpenFile(Db4oFileName); 05 try 06 { 07 for (int i = 0; i < 10; i++) 08 { 09 for (int j = 0; j < 5; j++) 10 { 11 Pilot pilot = new Pilot("Pilot #" + i, j + 1); 12 db.Set(pilot); 13 } 14 } 15 } 16 finally 17 { 18 db.Close(); 19 } 20 }

SortingExample.vb: SetObjects
01Private Shared Sub SetObjects() 02 File.Delete(Db4oFileName) 03 Dim db As IObjectContainer = Db4oFactory.OpenFile(Db4oFileName) 04 Try 05 Dim i As Integer = 0 06 While i < 10 07 Dim j As Integer = 0 08 While j < 5 09 Dim pilot As Pilot = New Pilot("Pilot #" + i.ToString(), j + 1) 10 db.Set(pilot) 11 System.Math.Min(System.Threading.Interlocked.Increment(j), j - 1) 12 End While 13 System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1) 14 End While 15 Finally 16 db.Close() 17 End Try 18 End Sub

The following topics discuss some of the possible methods and point out their advantages and disadvantages.