a sorting issue

by Jesse 13. November 2007 07:57

Ran into a really interesting gotcha some time ago and ran into it again.  It was rather irritating to go back and try to find the magical "how did I fix this?" so posting it was a good idea, and this is a great example of how something that makes perfect sense in code would produce a really strange, inconsistant "error" that you wouldn't expect.

So let's say you have a base class and there's a nullable datetime in there, "LastUpdatedDate" along with a nullable "CreatedDate" and a host of other junk that we don't care about right now.  The request is to retrieve the most recently updated item and at your disposal is a list of these items, we'll call it List<entry> entries.

entries.Sort(
delegate(Enty entry1, Entry entry2)
{
     
return entry2.LastUpdatedDate.Value.CompareTo(entry1.LastUpdatedDate.Value);
});

Well, bad news -- the LastUpdatedDate are equal.  How do you know when which entry comes out on top?  Did you say "that will never happen because of ticks, they will never be equal" ...not quite.  It's created on a database that you have no control over, IE its created on a trigger.  I ended up adding in another bit of logic to produce a more reliable output.  It isn't perfect.  Incase you are not fimiliar with CompareTo -- it returns a 1, a 0 or a -1.  1 is greater than, 0 is equal, -1 is less than, so we insert some logic into our anonymous method...

entries.Sort(delegate(Enty entry1, Entry entry2)
{
     int x = entry2.LastUpdatedDate.Value.CompareTo(entry1.LastUpdatedDate.Value);
     if (x == 0)
          return (entry2.CreatedDate.Value.CompareTo(entry1.CreatedDate.Value));
     else return x;
});

It's still possible that created date and last updated date could be equal, but the possibility is greatly reduced (in this case anyway).

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.Net | C# | Coding | Design

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

About the author

Like the description says, at my core, I'm a scientist and engineer.  I came from humble beginnings on a 486DX2 Packard Hell playing doom2 on IPX to in a small time retail shop and got into hardware (ISO layers FTW!) and it was all downhill from there.  I'm infinitely curious about almost everything and always wanting to know.

Some of the stuff I'm currently into/researching...

Sitefinity

Ninject

Subsonic

Java

Currently working on ...
i did the hundred 
and some extra stuff

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's, their brother nor their dog's view in anyway.  At all.  Ever.

© Copyright 2007-2008