C # binarysearch list <T> by member T

I have a base class Eventwith an element DateTime TimeStamp. Many other classes of events will come out of this.

I want to be able to quickly search for a list of events, so I would like to use binary search.

(List data is sorted by timestamp, but there may be repeated timestamps for events that occurred simultaneously)

So, I started 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 BinarySearch only accepts type T (so - a Event), and I want to search based on the member T - TimeStamp.

What would be a good way to approach this?

+5
source share
5

, comparer. T, .

inFromTime BinarySearch, , TimeStamp BinarySearch.

, , : ? binarysearch .

, . , :

  • , EventList IList.
  • BinarySearch IList .

, BinarySearch , . , , , . BinarySearch EventList, , .

: BinarySearch, , T, .

+1

- , IComparer<T>.

public class CompUtil : IComparer<T> {
  public int Compare(T left, T right) { 
    return left.TimeStamp.CompareTo(right.TimeStamp);
  }
}

int index = this.BinarySearch(inFromTime, new CompUtil());
0

Event , , . , , T, DateTime. Event DateTime, , , T , , .

, BinarySearch.

0
public class EventList<TEvent, TData>
   : List<TEvent> where TEvent : Event, TData: DataTime
{
   class Comparer : IComparer<TData> { } // as JaredPar mentioned above

   public IEnumerable<TEvent> EventsBetween(TData from, TData to) { }
}
0

Perhaps you could use SortedList as a base class instead of a list. You can then use the IndexOfKey method to search for the specified TimeStamp. This method performs a binary search.

0
source

All Articles