I have a hashtable and I want to loop through the keys to find one that matches my timer and then debug.log that value - I have this part working. How can I loop through it to find the next lowest key that matches the time if there is no exact match?
I’m currently using : if (myHashtable.ContainsKey(currentTime))
You can’t guarantee a Hashtable will keep keys sorted in a sensible order (depending on what your key type is). You’d have better luck keeping a separate structure (which contains just the keys used in your Hashtable) where the values are known to be in order (give [SortedList][1] a try). Then you can go through the sorted list and find the “closest without going over” key with something similar to the following:
//Handle some edge cases
if (sortedKeyList.Count == 0 || currentTime < sortedKeyList[0] || currentTime > sortedKeyList[sortedKeyList.Count - 1])
{
// Do whatever you'd do if you:
// have no keys entered,
// haven't passed the first key,
// or have past the last key.
}
else
{
MyKeyClass key;
for (int i = 1; i < sortedKeyList.Count; i++)
{
if (currentTime < sortedKeyList*)*
{ key = sortedKeyList[i - 1]; break; // or if you pull this into a utility function, skip the “key” variable and just return sortedKeyList[i - 1] } } } Then you can go to myHashtable[key] and use what’s there. [1]: SortedList Class (System.Collections) | Microsoft Learn