Native Query Sorting

Native Query syntax allows you to specify a comparator, which will be used to sort the results:

c#: 

IObjectSet Query(Predicate predicate, IComparer comparer);

VB: 

Function Query(ByVal predicate As Predicate, ByVal comparer As IComparer) As IObjectSet

In order to get the same results as in SODA Sorting example we will write the following code:

SortingExample.cs: GetObjectsNQ
01private static void GetObjectsNQ() 02 { 03 IObjectContainer db = Db4oFactory.OpenFile(Db4oFileName); 04 try 05 { 06 DateTime dt1 = DateTime.UtcNow; 07 IList<Pilot> result = db.Query<Pilot>(delegate(Pilot pilot) { 08 return true; 09 }, 10 new System.Comparison<Pilot>(delegate(Pilot p1, Pilot p2) 11 { 12 Pilot pilot1 = (Pilot)p1; 13 Pilot pilot2 = (Pilot)p2; 14 int res = pilot1.Points - pilot2.Points; 15 if (res == 0) 16 { 17 return pilot1.Name.CompareTo(pilot2.Name); 18 } 19 else 20 { 21 return -res; 22 } 23 })); 24 DateTime dt2 = DateTime.UtcNow; 25 TimeSpan diff = dt2 - dt1; 26 Console.WriteLine("Time to execute with NQ and comparator: " + diff.Milliseconds + " ms."); 27 ListResult(result); 28 } 29 finally 30 { 31 db.Close(); 32 } 33 }

SortingExample.vb: GetObjectsNQ
01Private Shared Sub GetObjectsNQ() 02 Dim db As IObjectContainer = Db4oFactory.OpenFile(Db4oFileName) 03 Try 04 Dim dt1 As DateTime = DateTime.UtcNow 05 Dim result As IObjectSet = db.Query(New AllPilots, New PilotQueryComparer) 06 Dim dt2 As DateTime = DateTime.UtcNow 07 Dim diff As TimeSpan = dt2 - dt1 08 Console.WriteLine("Time to execute with NQ and comparator: " + diff.Milliseconds.ToString() + " ms.") 09 ListResult(result) 10 Finally 11 db.Close() 12 End Try 13 End Sub
SortingExample.vb: AllPilots
1Private Class AllPilots 2 Inherits Predicate 3 Public Function Match(ByVal pilot As Pilot) As Boolean 4 Return True 5 End Function 6 End Class
SortingExample.vb: PilotQueryComparer
01Private Class PilotQueryComparer 02 Implements IQueryComparator 03 04 Public Function Compare(ByVal p1 As Object, ByVal p2 As Object) As Integer Implements IQueryComparator.Compare 05 If TypeOf p1 Is Pilot AndAlso TypeOf p2 Is Pilot Then 06 Dim pilot1 As Pilot = CType(p1, Pilot) 07 Dim pilot2 As Pilot = CType(p2, Pilot) 08 Dim result As Integer = pilot1.Points - pilot2.Points 09 If result = 0 Then 10 Return pilot1.Name.CompareTo(pilot2.Name) 11 Else 12 Return -result 13 End If 14 End If 15 Return 0 16 End Function 17 End Class

Advantages of NQ sorting:

  • type-safe queries and sorting, compile-time checking;
  • ability to implement any custom sorting algorithm

The main disadvantage is decreased performance.