Thursday
09Oct2008
Sorting Guid in .NET the way Microsoft SQL Server does it
Microsoft SQL Server sorts uniqueidentifier columns in a way that is different from the Guid ordering in .NET (see this post by Alberto Ferrari).
Here's a small C# code snippet from Lokad.Shared that implements Sql Server sorting of Guids in .NET.
public sealed class SqlServerGuidComparer : IComparer<Guid>
{
static readonly int[] _importance = new[] {3, 2, 1, 0, 5,
4, 7, 6, 9, 8, 15, 14, 13, 12, 11, 10};
public int Compare(Guid x, Guid y)
{
var a = x.ToByteArray();
var b = y.ToByteArray();
for (int i = _importance.Length - 1; i >= 0; i--)
{
var compare = _importance[i];
var c = a[compare].CompareTo(b[compare]);
if (c != 0)
{
return c;
}
}
return 0;
}
}
BTW, you could use this comparer in the Linq method OrderBy, that takes a reference of IComparer{T}.
Thursday, October 9, 2008 at 0:28
Reader Comments (2)
Funny, I did report this odd behavior as a bug to MS more than one year ago, see
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=291894
They finally closed the bug as "can't reproduce" not even having a look at the small that I did give them :-(
I would've expected something like: "this is known behavior and it will stay this way for the backwards compatibility" or simply "SQL and .NET teams could not figure out who's to fix this one".
But simply closing the issue is cold.