c# binarysearch a list<T> by a member of T

Posted by Pygmy on Stack Overflow See other posts from Stack Overflow or by Pygmy
Published on 2010-04-02T09:04:24Z Indexed on 2010/04/02 9:13 UTC
Read the original article Hit count: 380

Filed under:
|
|
|
|

I have a baseclass Event with a DateTime member TimeStamp. Lots of other event-classes will derive from this.

I want to be able to search a list of events (that can contain events with duplicate timestamps) fast, so I'd like to use a binary search.

So I started out writing something like this :

public class EventList<T> : List<T> where T : Event
{
   private IComparer<T> comparer = (x, y) => Comparer<DateTime>.Default.Compare(x.TimeStamp, y.TimeStamp);

   public IEnumerable<T> EventsBetween(DateTime inFromTime, DateTime inToTime)
   {
       // Find the index for the beginning. 
       int index = this.BinarySearch(inFromTime, comparer);

       // BLAH REST OF IMPLEMENTATION
   }
}

The problem is that the BinarySearch only accepts T (so - an Event type) as parameter, while I want to search based on a member of T - the TimeStamp.

What would be a good way to approach this ?

© Stack Overflow or respective owner

Related posts about c#

Related posts about binary