December 18, 2008

GUID Sorting

I just found out (the hard way) that .Net and MSSQL sort GUIDs differently. Basically, the sql GUID only compares the last 6 bytes of the GUID where the .net GUID compares all 16 bytes. (MSDN: Working with GUIDs)

Here's what I was trying to do when I discovered this:

I had a collection of objects of type A. These Objects contained a field, A.Guid, that was of type GUID. I also had a collection of objects of type B. These objects also contained a GUID field called B.Guid. I needed to check if A.Guid == B.Guid for each object in both A and B. I didn't want to make my code O(n^2) so I decided to sort each collection. One of the collections was retrieved from an MSSQL database (collection B) and one already existed (collection A). So, I figured that I would just use an Order By command in my SQL query to sort collection B by GUID and the ArrayList.Sort command to sort collection A. Once the collections were sorted, I would simply iterate through one of the lists and compare the values of one list at the current index the values of the other list at the same index (this isn't exactly what I did, but it's pretty close).

As you may have guessed, this didn't work out. However, once I changed the algorithm so that both A and B were using the same sort function, everything worked out perfectly.

So, what I'm trying to say here to save people the frustration I just experienced:

MSSQL DOES NOT SORT GUIDS THE SAME WAY .NET DOES!

Ps. I was using .Net 3.5