views:

493

answers:

3

what's a nice, fast way to sort a list of GUIDs (as TGuid). i thought i'd just use SysUtils.CompareMem(P1, P2: Pointer; Length: Integer): Boolean; until i realized it returns boolean.

i'd wish for something comparable to CompareText( ) or CompareValue( ) that return integer so it can be used in a sort comparison.

i suppose not many people wish to sort GUIDs...any ideas?

i suppose i could call make some cascading calls to CompareValue( ) on the contents of the TGuid record. my instincts tell me there must be a better way!

thank you!

+2  A: 

I do not know Delphi but generally a GUID is a 128-bit hexadecimal string, you can just cast/parse the sub-elements to unsigned (4 * 4-byte or 2*8-byte) integers and then compare them. Once you have that function just apply a standard sort algorithm.

If my answer does not satisfy the RFC of the GUID specification Microsoft uses is presented here, you can probably come up with better ways of sorting extracting the bit-level data in the GUID.

Hassan Syed
This is the best option if < Delphi 2009 as a string comparison too expensive. Just have your routine bail early as soon as a missmatch is found since for a majority of these it won't be necessary to sort much past the first or second element.
skamradt
+10  A: 

If you're using Delphi 2009 or better, you can use TComparer<TGUID>.Compare(), or the BinaryCompare function it calls, from the Generics.Defaults unit.

Barry Kelly
very smooth barry--thank you! i knew there must be something i could use for this in the RTL!
X-Ray
A: 

Use GUIDToString and do CompareStr on that -- not the fastest option but it works.

Frederik Slijkerman
Ouch...string comparisons are VERY expensive. Better to sort against the TGUID elements individually, or cast to an array of [1..8] integer and compare the arra
skamradt