/// <summary> /// Scans for the location of an item within the internal list. /// </summary> /// <remarks> /// Performs a binary search within the list with forward and backward scanning. /// Will throw an exception if item is not found. USE ONLY to find an item by key when you KNOW it's there. /// </remarks> /// <param name="Key">Item Key</param> /// <param name="entryValueItem">The Item Value</param> /// <returns>The zer-based index of the items location</returns> private int BinaryLocate(TKey Key, TimeTaggedItem <TValue> entryValueItem) { int index = list.BinarySearch(new TimeTaggedItem <TKey>(entryValueItem.TimeStamp, Key)); if (index < 0) { throw new InvalidOperationException("Use BinaryLocate only when the item exists in the List"); } //This might not be the one corresponding to the right key int b = 0, f = 0; while (!list[index].Value.Equals(Key)) { //So scan backwards and forwards silmultaneously b++; f++; if (index - b >= 0) { if (list[index - b].Value.Equals(Key)) { index = index - b; break; } } if (index + f <= list.Count - 1) { if (list[index + f].Value.Equals(Key)) { index = index + f; break; } } if ((index + f > list.Count - 1) && (index - b < 0)) { throw new InvalidOperationException("Use BinaryLocate only when the item exists in the List"); } } return(index); }
/// <summary> /// Adds or updates an item in the dictionary /// </summary> /// <param name="TimeStamp">The timestamp to set for the item</param> /// <param name="Key">The Item Key</param> /// <param name="Value">The Item Value</param> public void Add(DateTime TimeStamp, TKey Key, TValue Value) { lock (sync) { TimeTaggedItem <TValue> entryValueItem; if (dict.TryGetValue(Key, out entryValueItem)) { //This item exists so update both dictionary and list //First update list //Look for existing item using the found entry int index = BinaryLocate(Key, entryValueItem); //Remove it list.RemoveAt(index); //Reinsert it in the right place in the ordered timestamp list //1. Look for next largest item in list for the new timestamp TimeTaggedItem <TKey> listItem = new TimeTaggedItem <TKey>(TimeStamp, Key); index = list.BinarySearch(listItem); //2. Insert it there list.Insert(index < 0 ? ~index : index, listItem); //Secondly update dictionary with the value dict[Key] = new TimeTaggedItem <TValue>(TimeStamp, Value); } else { //This item does not exist so insert into both dictionary and list //First insert into list //Look for next largest item in list TimeTaggedItem <TKey> listItem = new TimeTaggedItem <TKey>(TimeStamp, Key); int index = list.BinarySearch(listItem); //Insert it there list.Insert(index < 0 ? ~index : index, listItem); //Secondly insert into dictionary dict.Add(Key, new TimeTaggedItem <TValue>(TimeStamp, Value)); } } }
public int CompareTo(TimeTaggedItem <T> other) { return(TimeStamp.CompareTo(other.TimeStamp)); }