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?
, comparer. T, .
inFromTime BinarySearch, , TimeStamp BinarySearch.
, , : ? binarysearch .
, . , :
- , EventList IList.
- BinarySearch IList .
, BinarySearch , . , , , . BinarySearch EventList, , .
: BinarySearch, , T, .
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.